Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

transform.Translate & transform.position

Discussion in 'Scripting' started by Deleted User, Jun 1, 2015.

  1. Deleted User

    Deleted User

    Guest

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class GetAxis : MonoBehaviour {
    5.  
    6.     private float MoveOnX;
    7.     private float MoveOnY;
    8.  
    9.     void Update () {
    10.         MoveOnX = Input.GetAxis ("Horizontal");
    11.         MoveOnY = Input.GetAxis ("Vertical");
    12.  
    13.         transform.Translate(MoveOnX  * Time.deltaTime, MoveOnY * Time.deltaTime, 0);
    14.         transform.position = new Vector3 (MoveOnX, MoveOnY, 0);
    15.     }
    16.  
    17. }
    Can someone please explain to me why when using the line that starts with transform.Translate allows an object to move further than -1 to 1 and it doesn't return to 0?

    Also why when using the transform.position = new Vector3.....I can not move further than -1 or 1 and it returns to 0?

    One last thing is that I don't understand why when using the Time.deltaTime in the 1st line it moves smoothly and when using it in the 2nd line it barely moves.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,735
    transform.Translate is relative - it moves an object by the amount given. If you move it by (1,0,0), then by (1,0,0), then by (1,0,0) again, it gets moved by (3,0,0) ultimately.

    Setting transform.position is absolute - it just sets the position. You can set transform.position to (1,0,0) all day long and it'll always stay at (1,0,0).

    Time.deltaTime means the time between the last frame and this one in seconds. It's a very small number (around 0.03 usually, smaller if you are working at a faster framerate). When you multiply it into a Translate(1,0,0) that is used in Update, what you are essentially mathematically saying is, "move this by a total of (1,0,0) over the course of one second".
     
    albertoha94 likes this.
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,735
    I suspect that part of your confusion comes from Unity's input smoothing. When you press the right arrow key and use GetAxis("Horizontal") to get that value, it doesn't go directly from 0 in one frame to 1 the next frame after you press the arrow; it smoothly moves it up there over a couple of frames. If you use GetAxisRaw instead you'll see a much direct representation of the input.
     
  4. lingmoumax

    lingmoumax

    Joined:
    Apr 17, 2021
    Posts:
    1
    3Q for your reply,it makes me to understand this.