Search Unity

(3d) Moving diagonally is faster?

Discussion in 'Physics' started by DarkOmen20, Jan 3, 2020.

  1. DarkOmen20

    DarkOmen20

    Joined:
    Dec 31, 2019
    Posts:
    5
    I know I know, it's been asked a million times, but I've literally spent 3 days scouring the internet and I can't find a definitive solution, so here goes...

    I have a kinematic gameobject I'm trying to move on the x,z plane with WASD (or arrow keys) relative to player orientation.

    I've set speed to 10 in Unity, and moving in a straight line produces exactly 10 velocity when logged. The problem (I think...?) is with diagonal movement. I've normalized the vector prior to multiplying speed and deltaTime, but if you add the forward and lateral move speeds during diagonal movement it still comes to about 40% faster than moving in a single direction.

    Here's the script, followed by a sample line from the console while both 'w' and 'd' were pressed:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerController : MonoBehaviour
    4. {
    5.  
    6.     public float speed;
    7.  
    8.     private Rigidbody rigidBody;
    9.     private Vector2 input;
    10.  
    11.     private void Awake()
    12.     {
    13.         rigidBody = GetComponent<Rigidbody>();
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         input = new Vector2();
    19.         if (Input.GetKey(KeyCode.A)) { input.x = -1; }
    20.         if (Input.GetKey(KeyCode.D)) { input.x = 1; }
    21.         if (Input.GetKey(KeyCode.W)) { input.y = 1; }
    22.         if (Input.GetKey(KeyCode.S)) { input.y = -1; }
    23.     }
    24.  
    25.     private void FixedUpdate()
    26.     {
    27.         Vector3 movement = transform.right * input.x;
    28.         movement += transform.forward * input.y;
    29.         movement.Normalize();
    30.  
    31.         movement *= speed * Time.fixedDeltaTime;
    32.  
    33.         rigidBody.MovePosition(rigidBody.position + movement);
    34.  
    35.         Vector3 myVelocity = rigidBody.velocity;
    36.         Debug.Log(myVelocity);
    37.     }
    38. }
    39.  

    (7.1, 0.0, 7.1)
    UnityEngine.Debug:Log(Object)


    I am admittedly fairly new to programming, very new to Unity, and not especially strong in physics lol. Any feedback or advice would be greatly appreciated!

    - a fellow game lover tryin' to make one
     
    vihaansengupta2710 likes this.
  2. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,512
    Everything is correct. I can't see any 40% speed increment in your code nor in the debug output. Doing the math with [7.1, 0.0, 7.1] results in a speed of 10 m/s. The calculation with those numbers is ~10.04, but that's because the vector string shows one decimal only by default.

    Why don't you simply log the velocity magnitude? That's the actual speed of movement.
    Code (CSharp):
    1. Debug.Log(myVelocity.magnitude)