I have a top down space shoot game that is currently allowing movement in all directions. That is front, back, side to side, and diagonal. All my movements are working correctly but I am wanting to implement space like physics to the game to where if my ship is traveling forward and I let go of the forward button my ship should still be drifting in the same direction. This needs to be the same for all directions even diagonal. I’ve tried using
transform.position += transform.forward * driftSpeed * Time.deltaTime;
which works for forward and diagonal movements since the ship is pointing in the direction it is going. However, if I am strafing side to side or in reverse the ship drifts in the direction the front of the ship is pointed. Is there a way to apply this drift in the direction the ship is currently heading instead of where the front is pointing? Btw I am currently using transform.Translate for my movements instead of rigidbody.
Currently you’re adding a forward vector multiplied by your drift speed (transform.forward * driftSpeed) to your position. You’ll need to check which direction the ship is currently moving and add that to your position.
Ex. If you’re moving left
transform.position += transform.left * driftSpeed * Time.deltaTime;
Just swap out transform.left for whatever direction you’re currently moving.
Well Ive been be doing similar movement in several projects now, and my advice would be to use the built-in physics engine, because it gives you everything you need in a matter of minutes.
Just set up a moving rigidbody and apply force to it, then tinker with mass / drag / angular drag, until you got the behaviour you want. You should go with a very low drag/angular drag for this kind of movement.
(in addition to what Otsego said)
If you want to use direct movement however, the route to go would be to store the driftspeed as a Vector3 and and to assign the controller movement vector to it, each time a control event happens. It will be a bit of waste of time and work though, as the physics engine can simulate this much more easily and will give you a very smooth inertia system.
Another way of doing this code-wise would be to use a coroutine to monitor the current movement vector and add it in a decreasing fashion to the next movement step. But Id recommend to use the physics engine!