## Posts Tagged ‘htc’

### 蛋疼的小球 – 重力感应器小试牛刀

x2的坐标则可以用x2=x1+(t2-t1)*(vx1+vx2)/2 来计算，即位移等于平均速度乘以时间。

```// http://www.diy-robots.com
// apply physics to a ball
Ball ApplyDevicePhysics(GVector gVector, Ball ball, int millisecondsElapsed)
{
int maxX = ClientSize.Width - ball.Radius;
int maxY = ClientSize.Height - ball.Radius;
double t = millisecondsElapsed / 1000.0;

#region calculate x values
gVector.X *= frictionForce;
double v1 = ball.Velocity.X;
double x1 = ball.Position.X;
ball.Velocity.X = v1 + gVector.X * t;
ball.Position.X = x1 + v1 * t + 0.5 * gVector.X * t * t;
{
if (ball.Velocity.X < 0)
{
ball.Velocity.X *= (-elasticRation);
if (gVector.X < 0 && (-ball.Velocity.X / gVector.X) < (t * 2 * elasticRation))
{
ball.Velocity.X = 0;
}
}
}
if (ball.Position.X > maxX)
{
ball.Position.X = maxX;
if (ball.Velocity.X > 0)
{
ball.Velocity.X *= (-elasticRation);
if (gVector.X > 0 && (-ball.Velocity.X / gVector.X) < (t * 2 * elasticRation))
{
ball.Velocity.X = 0;
}
}
}
#endregion

#region calculate y values
gVector.Y *= frictionForce;
v1 = ball.Velocity.Y;
double y1 = ball.Position.Y;
ball.Velocity.Y = v1 + gVector.Y * t;
ball.Position.Y = y1 + v1 * t + 0.5 * gVector.Y * t * t;
{
if (ball.Velocity.Y < 0)
{
ball.Velocity.Y *= (-elasticRation);
if (gVector.Y < 0 && (-ball.Velocity.Y / gVector.Y) < (t * 2 * elasticRation))
{
ball.Velocity.Y = 0;
}
}
}
else if (ball.Position.Y > maxY)
{
ball.Position.Y = maxY;
if (ball.Velocity.Y > 0)
{
ball.Velocity.Y *= (-elasticRation);
if (gVector.Y > 0 && (-ball.Velocity.Y / gVector.Y) < (t * 2 * elasticRation))
{
ball.Velocity.Y = 0;
}
}
}
#endregion
return ball;
}
```