FloodAndBones
FloodAndBones

Reputation: 17

How to Vector3.normalized only if exceeding -1/1?

So I am currently creating movement for a character and all is well except diagonal movement is doubled because it is obviously combining vertical and horizontal movement. Now I did try normalizing the Vector3, but that results in a delayed stop for the character. According to other forums I read, I think it's because it should only normalize when it is greater/less than -1/1 but I don't know how to setup this constraint. Please help!

forwardInput = Input.GetAxis("Horizontal");
horizontalInput = Input.GetAxis("Vertical");

Vector3 movement = new Vector3(horizontalInput, 0, forwardInput).normalized * speed * Time.deltaTime;
transform.Translate(movement);

Upvotes: 0

Views: 1388

Answers (1)

derHugo
derHugo

Reputation: 90580

Problem with always normalizing is that you move with the same speed no matter how far the input is pressed.

This is no problem on a PC with keyboard input which is either 0, -1 or 1 but will not work as expected if e.g. using a controller since it will also round up the value in case you normalize if the original input vector's magnitude is smaller then 1.

So yes you should normalize only in case the magnitude of the input vector exceeds 1 e.g. when pressing in two directions at the same time in order to maintain a certain maximum speed. In order to not type redundant code I would rather separate the vector and assignment in different variables and use Vector3.Normalize instead:

forwardInput = Input.GetAxis("Horizontal");
horizontalInput = Input.GetAxis("Vertical");

var inputVector = new Vector3(horizontalInput, 0, forwardInput);

// note that a magnitude is always positive, there is no -1
// if magnitude > 1 then implicitely also sqrMagnitude > 1 and the other way round
// sqrMagnitude is faster to access then magnitude and for this check
// here provides the same result 
if(inputVector.sqrMagnitude > 1) inputVector.Normalize();

var movement = inputVector * speed * Time.deltaTime;
transform.Translate(movement);

Upvotes: 2

Related Questions