Reputation: 703
I'm trying to animate a 2d sprite in my XNA 2D game, by the force of gravity. I've developed a very basic class to achieve the simulation effect. This is my sample code.
namespace Capture
{
class PhysX
{
static Vector2 g = new Vector2(0.0f, 10.0f);
public Vector2 pos, vel, acc, accumForce;
public float mass;
public bool USE_GRAVITY = true;
/* Constructor */
public void Engage(ref GameTime gameTime, uint maxX, uint maxY)
{
Vector2 F = Vector2.Zero;
if (USE_GRAVITY)
{
F = accumForce + mass * g;
}
acc = F / mass;//This is the Net acceleration, Using Newtons 2nd Law
vel += acc * gameTime.TotalGameTime.Seconds;// v = u + a*t
pos += vel * gameTime.TotalGameTime.Seconds;// s = u*t + 0.5*a*t*t,
pos.X %= maxX;
pos.Y %= maxY;
}
public void ApplyForce(ref Vector2 f)
{
accumForce += f;
}
}
}
I'm calling the PhysX#Engage()
method in Game#Update(GameTime gt)
method.
The problem is this I'm not getting a smooth animation. This is because the position gets very large soon. To, overcome that I tried to take modulus, as show in the code with the Viewport.Width, Viewport.Height
but still the position coordinates are not at all smooth. What should I do. How to make animation smooth? Please help.
Upvotes: 5
Views: 2234
Reputation: 39164
I think that's happening because you are taking elapsed time value as integer.
Try use double value of seconds that takes into account even the fractionary part:
flaot dt = (float)GameTime.ElapsedGameTime.TotalSeconds;
vel += acc * dt;// v = u + a*t
pos += vel * dt;// s = u*t + 0.5*a*t*t,
In addition:
This is because the position gets very large soon.
Well, you should keep the float value as close as possible to [-1,+1] range, otherwise you will get a loose of precision. My advice is:
Upvotes: 3