- Home /
After normalizing a vector, Character not as responsive.
Good afternoon.
I had this small bit of code which detects which way my character is moving.
var targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity *= speed;
After testing it I found that moving diagonally would speed the player up so I changed the code to this
var targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity = targetVelocity.normalized;
targetVelocity *= speed;
But now for some reason when I let go of the arrow key or stick moving the character there is a delay in him stopping. Does anyone know why this might be. The fulll code is below.
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity = targetVelocity.normalized;
targetVelocity *= speed;
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0.0f;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
Thank you!
Edit: After testing again I have found that without the normaize it takes as long to slow down but does so at a gradual pace rather than delay then dead stop.
Answer by NoseKills · Feb 12, 2015 at 07:23 AM
You probably only want to normalize the vector when it's longer than one.
Normalizing the vector forces its lenght to 1 even when it's shorter than 1, so it prevents your velocity from slowing down as well as growing too big.
Thanks for this. $$anonymous$$odified the code to only normalize when the vector is more than 1 or less than -1