Saturday, April 22, 2017

xna - How to create simple acceleration in a 2D sprite?



So here's what I thought might work but half the time I press the 'Right' key, it results in a crash and the rest of the time seems to produce no acceleration at all.


if (KeyboardState.IsKeyDown(Keys.Right))

while (motion.X < 1)
motion.X += 0.001f + motion.X;


I want to know why exactly it won't work, and any possible alternate algorithms.



Answer



To implement basic acceleration you need to know a little physics. The basics you need to know about are the relationships between:



  • Position - Where your object is

  • Velocity - The direction and rate your object is changing its position

  • Acceleration - The direction and rate your object is changing its velocity


So, to add acceleration, you need to have Position and Velocity already implemented. I'll assume you're doing that already, since you're asking about Acceleration.



Since you have velocity already implemented, I'll assume you have something like:


player.x += player.velocity.x * dt;
player.y += player.velocity.y * dt;

Where dt is the time since the last update. Now if we want to change the velocity with respect to time, we just need to add a line like this:


player.velocity.x += player.acceleration.x * dt;
player.velocity.y += player.acceleration.y * dt;

Now, if we want to modify that acceleration with the keyboard, we can do something simple like:


if (KeyboardState.IsKeyDown(Keys.Right))

player.acceleration.x += .01f;

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...