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 :stuck_out_tongue:

It's 3D btw :P

You should normalize the input vector. Like so... float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector2 inputVector = new Vector2( h, v ); inputVector.Normalize(); Then multiply it by your desired speed and use that to move the character. This will correct the issue. Best,

3 Answers

3

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 Mouse for example. I'd recommend using [ClampMagnitude][1] instead. [1]: https://docs.unity3d.com/ScriptReference/Vector2.ClampMagnitude.html

@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 ClampMagnitude instead of normalizing. Replace moveDirection.Normalize(); with moveDirection = Vector3.ClampMagnitude(moveDirection, 1);

Thanks so much :D

Also discussed here