Unity – Translate GameObjects
Translate Meters x frame
DRAG AND DROP this script over a object in the Hierarchy:
#pragma strict function Update () { transform.Translate(new Vector2(1,0)); }
Statement: transform.Translate(new Vector2(1,0)); -> transform.Translate(new Vector2(x,y));
It adds 1px of ‘x’ value of the 2D Vector. The object moves quickly because the transformation command is inside Update(), it means the code adds 1px every frame.
Translate Meters x seconds
DRAG AND DROP this script over a object in the Hierarchy:
#pragma strict function Update () { transform.Translate(new Vector2(1,0)*Time.deltaTime); }
NOTICE: *Time.deltaTime -> It converts the movement from meters x frame to meters x second
Translate Meters x frame + add velocity
DRAG AND DROP this script over a object in the Hierarchy:
#pragma strict public var moveSpeed : float = 10f; function Update () { transform.Translate(new Vector2(1,0)* moveSpeed *Time.deltaTime); }
Invert movement
#pragma strict public var moveSpeed : float = 10f; public var xpos : float = 1; public var ypos : float = 1; function Update () { transform.Translate(new Vector2(xpos,ypos)* moveSpeed *Time.deltaTime); }
NOTICE:
xpos= 1 move right
xpos= -1 move left
ypos= 1 move up
ypos= -1 move down
Vector2.right – Vector2.up
Vector2.right -> it this the same of -> new Vector2(1,0)
Vector2.up -> it this the same of -> new Vector2(0,1)
You can write:
#pragma strict public var moveSpeed : float = 10f; public var xpos : float = 1; public var ypos : float = 1; function Update () { transform.Translate(xpos*Vector2.right * moveSpeed * Time.deltaTime); transform.Translate(ypos*Vector2.up * moveSpeed * Time.deltaTime); }
NOTICE:
xpos= 1 move right
xpos= -1 move left
ypos= 1 move up
ypos= -1 move down