Unity 2D simple Acceleration and Deceleration
I’m making a top-down 2D space shooter and I wanted the movement to feel really great and give myself some flexibility. I tried the Unity physics systems but it didn’t give me the feel I wanted. So I implemented some simple physics movement; it feels much better and can be easily adjusted.
For this you will need a few variables to make it work:
I use the Unity input system to constantly update the player movement vector and I have a very simple Move method to update the player acceleration and direction.
In the move method, I am setting my velocity variable and then I am clamping the velocity to be either velocity or the speed variable. Whichever is smaller.
Next in my update method, I check whether the movementVector(player input) is zero. If it is zero that means the player has let go of the keys/buttons to move and I can start the deceleration.
Here I create a decelVector and then normalise the velocity so that it has a magnitude of 1. I then * it by the amount in the decel variable. The result is a vector that represents the amount of velocity that should be removed per second in the direction opposite to the current velocity.
The decelVector is then removed from the velocity vector and the player will slow down. The higher the decel variable is set to, the quicker the player will slow down.
The last thing to do is to move the player:
The _t above is the player transform. I cache my transforms for objects that are constantly moving because if you use transform.position, that is the same as making a get component assignment. So, caching the transform gives a better performance. Especially, if you have lots of objects moving around the screen.
And that is it for moving a 2D object with acceleration and deceleration, take a look at my other articles.