I use build-in Joystick. The controller handler looks like this:

public void Move(Vector2 direction) { transform.Translate(direction * Time.deltaTime * Speed); } 

Faced a problem: when direction in call chains has the same value (for example, Vector2(1f, 0f) ), that is, the object moves in the same direction, then the speed of the object is the same. But as soon as I start pulling the joystick controller along the Y axis ( Vector2(1f, anyf) ), the object starts moving faster along the X axis. Why is this happening and how to fix it?

  • It depends how you calculate the direction - Eugene Bartosh
  • as I wrote above, I use the built-in component Joystick and I need to throw a method into it, in this case I’ve thrown the method Move - dakiesse

1 answer 1

Having a little understood the topic, I learned that there is such as the "length" of the vector, or else the "module" of the vector.

Take two vectors:
V(1, 0) - we want to give the object a direction along the X axis to the right ( )
V(1, 1) - up and to the right ( )

Calculate the length of the vectors:
|a| = √1² + 0² = √1 + 0 = √1 = 1 |a| = √1² + 0² = √1 + 0 = √1 = 1 .
|a| = √1² + 1² = √1 + 1 = √2 ≈ 1.4142135623730951

The second vector is the longest, and it is precisely due to this that the object moves faster when moving right-up. To solve this problem, you need to normalize the vector: Vector3.Normalize(myVector) .

Result code:

 public void Move(Vector2 direction) { transform.Translate(Vector3.Normalize(direction) * Time.deltaTime * Speed); }