Character Diagonal Movement Issue
I've made a movement script + jumping but it seems like when I move diagonally (W + D/A) or (S + D/A) my character moves twice as fast as normal. I get it's because in the script I've done:
moveDirection *= speed;
So it basically multiplies the moveDirection by speed, but when I press 2 keys like W and D I think it kinda multiplies both of the keys or the directions so it equals to twice as much as normal. How do I fix this? Or maybe I'm just seeing things and I'm actually moving normally? Thanks in advance :P
Answer by AlwaysSunny · Dec 28, 2016 at 02:47 PM
You should normalize the input vector. Like so...
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 inputVector = new Vector2( h, 0, v );
inputVector.Normalize();
Then multiply it by your desired speed and use that to move the character.
This will correct the issue.
Think of it like this: Without normalization, the input vector fits into a square. The corners of a square are further from the center than the middle of the edges are. Normalizing "chops off" the excess, so the final input vector fits into a circle, making the vector a uniform length no matter what direction it's pointing.
Best,
Using Vector3.Normalize() will result in a Length that is always equal to one. Thus preventing subtle motion when using Joysticks or $$anonymous$$ouse for example. I'd recommend using Clamp$$anonymous$$agnitude ins$$anonymous$$d.
Excellent point! Saw WASD and forgot about Clamping. :)
Answer by Tronline · Dec 28, 2016 at 02:57 PM
@AlwaysSunny Oh ok! I get it now, thanks!
Addressing your comment about clamping here, because UA only lets you reply so many levels deep.
You should use Clamp$$anonymous$$agnitude ins$$anonymous$$d of normalizing. Replace
moveDirection.Normalize();
with
moveDirection = Vector3.Clamp$$anonymous$$agnitude(moveDirection, 1);
Answer by IntergalacticSloth · May 18, 2018 at 05:52 AM
Also discussed here https://answers.unity.com/questions/639075/using-move-the-enemy-moves-faster-at-a-diagonal.html