Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Question Input in world/local space?

Discussion in 'Scripting' started by Geekguy100, Sep 19, 2020.

  1. Geekguy100

    Geekguy100

    Joined:
    Aug 18, 2012
    Posts:
    6
    Hello!
    I was working on a player controller script from a tutorial when a part of the code confused me.
    First, we create an input Vector3 which takes in player input from the keyboard, and with that assign a velocity vector by multiplying input*moveSpeed.
    When I write
    transform.position += velocity * Time.deltaTime;
    the character moves in the direction of the world coordinates (I had the player game object selected and enabled global, not local, rotation in the editor and saw it was following the proper axes), which I expected, and regardless of the player's rotation, it still moves in the same direction.
    To make the player walk in the direction it's facing, we type
    velocity = transform.TransformDirection(velocity);
    but transform.TransformDirection() says that it transforms direction from LOCAL space to world space. I thought since before this line of code was implemented, the player was walking in the direction of world coordinates, and I would need to convert from world to local space.

    Can anyone help explain why the direction is in local space to begin with, and why I must transform it to world space in order for the player to move with rotation in mind?

    Thanks.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerMovement : MonoBehaviour
    4. {
    5.     private Vector3 velocity;
    6.     [SerializeField] private float moveSpeed = 5f;
    7.  
    8.     private void Update()
    9.     {
    10.         var input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    11.         velocity = input * moveSpeed;
    12.  
    13.         velocity = transform.TransformDirection(velocity);
    14.  
    15.         transform.position += velocity * Time.deltaTime;
    16.     }
    17. }