I’m working on rigidbody player movement and need some advice. Here’s my issue:
When I hold “W”, the player’s velocity increases until it reaches the max speed. However, when I press “W” and “A” together, I use Vector3.MoveTowards to change the player’s velocity to the new direction. During this transition, the player’s speed drops below the max speed until it reaches the new velocity.
I want the player to maintain max speed (or accelerate to it if not already there) even when changing directions, such as from Vector3(1, 0, 0) to Vector3(1, 0, 1), but not from Vector3(1, 0, 0) to (-1, 0, 0).
I’m not sure how to achieve this. I’ve tried normalizing the new movement vector and multiplying it by the current/max velocity, but this approach results in unwanted behavior. Specifically, I don’t want the player to maintain max speed if they change direction from forward to backward.
I assume you’d like to have super snappy movement for small changes in direction (like 45 degrees when you go “north” and then “north west”) but still want to keep some realism when completely changing direction. I suggest you calculate the angle between the current velocity of the rigidbody and the steering direction:
// Just a suggestion to transform the movement vector into world space instead of multiplying with
// Quaternions for better readability. You probably need to change something here to fit your controls.
var moveDirection = cam.TransformDirection( new Vector3( inputx, inputy, 0f) );
var angle = Vector3.Angle(moveDirection, rigidbody.velocity)
if (angle < 50) {
// handle movement while keeping velocity
var limitedMoveSpeed = Vector3.ClampMagnitude(moveSpeed, rigidbody.velocity.magnitude);
rb.AddForce(limitedMoveSpeed - rb.velocity, ForceMode.VelocityChange);
}
// add force to the rigidbody like you normally would
I didn’t test this, but this would be my first try.
I’m not 100% of the logic behind this but it seems like you are subtracting the dot product of the desired velocity and the current velocity and multiplying that by the normalized desired vector which will add less force to the rigidbody the closer I get to the desired velocity. This isn’t my goal as it still loses speed when changing directions from moving forward to moving diagonally forward.
I tried something similar to this but it leads to undesired inconsistencies when moving between angles 49 and 51. I think I need some sort of speed threshold depending on how close to the current velocity the desired velocity is but I’m not sure on standard implementation methods.