I have this code. The idea is that it checks if I moved last FixedUpdate (all of this code is in FixedUpdate) and if I did, it will subtract the movement speed from the velocity to get the speed of the momentum I had without the walk speed added. So if I added a dash or something, I could walk and the dash momentum would be added to my walk speed. lastMoveDirection is used so that it gets the momentum with the last walk speed removed instead of the current one.
But when I actually walk it’s very strange and does not work. Sometimes I can walk in one direction normally but then it gets messed up and I start moving really slowly, and sometimes I can’t stop moving. I don’t know where my math is wrong.
You’ve tagged your post 2D Physics but the code looks like it’s for moving a 3D rigidbody. If you want the rigidbody to maintain momentum then you may find it easier to move it around with AddForce.
This code seems fairly complicated for what I imagine can be distilled down to “increase value if input, decrease value if no input”. You only just need a target velocity vector, and you can increase/decrease separate velocity vector depending on what input is present.
Worth pointing out this is just the same as using transform.forward and transform.right.
Though in situations with physics, you want to read position and rotation values off the rigidbody instead. A rigidbody doesn’t gave these same direction properties, but you can easily do the same with the Quaternion * Vector3 operator to rotate a direction based on a rotation. Eg, the equivelant of transform.forward is just Rigidbody.rotation * Vector3.forward.
Also worth mentioning that Vector2 and Vector3 have a bunch of operators like other integral values. moveDirecton.x != 0 || moveDirection.y != 0 can be simplified to just moveDirection != Vector3.zero.
That said, as Zulo said you ought to clarify if this is 2d or 3d physics.
I use addForce for other stuff but I don’t know how I would use it for walking because I want the walk speed to be constant. How would I do walking with addForce without the player constantly gaining more walk speed from the walk speed adding onto itself?
I figure you’d just have a private Vector3 _currentWalkSpeed; and increase/decrease that based on input. Then if the player is indeed ‘walking’, that’s used to drive the velocity, though don’t know if I fully understand how you intend for this to work.
You can cut off or taper off the force as the player gets closer to a target velocity.
I will point out that using forces and directly controlling rigidbody velocity can have its issues. Namely controlling velocity will override forces. Very often you need to go all in on one or the other.
You can set the rigidbody’s drag setting. Typically you would do this from script so the character has drag while on the ground and no drag while in the air.
Or do as Spiney suggests and reduce the input force as the character’s velocity increases. The Quake games did this.