0
0
UnityHow-ToBeginner ยท 3 min read

How to Use transform.Translate in Unity for Object Movement

Use transform.Translate(Vector3 direction) in Unity to move an object by a specified amount in world or local space. It changes the object's position by adding the direction vector to its current position each frame or call.
๐Ÿ“

Syntax

The transform.Translate method moves an object by a given vector. It has several overloads, but the basic syntax is:

  • transform.Translate(Vector3 translation) - moves in local space by default.
  • transform.Translate(Vector3 translation, Space relativeTo) - specify Space.World or Space.Self for world or local space movement.

Parameters:

  • translation: The amount and direction to move the object.
  • relativeTo: Optional. Defines if movement is relative to the world or the object's local axes.
csharp
transform.Translate(Vector3 translation, Space relativeTo = Space.Self);
๐Ÿ’ป

Example

This example moves a game object forward continuously when the game runs. It uses transform.Translate inside the Update method to move the object along its local z-axis.

csharp
using UnityEngine;

public class MoveForward : MonoBehaviour
{
    public float speed = 5f;

    void Update()
    {
        // Move the object forward at 'speed' units per second
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }
}
Output
The game object moves forward smoothly at 5 units per second while the game runs.
โš ๏ธ

Common Pitfalls

Some common mistakes when using transform.Translate include:

  • Not multiplying by Time.deltaTime, causing movement speed to depend on frame rate.
  • Confusing local and world space, which can make the object move in unexpected directions.
  • Using transform.position += instead of transform.Translate when you want relative movement.

Always decide if you want movement relative to the object (Space.Self) or the world (Space.World).

csharp
/* Wrong: Movement speed depends on frame rate */
void Update()
{
    transform.Translate(Vector3.forward * 5); // Moves too fast or slow on different devices
}

/* Right: Movement speed consistent across devices */
void Update()
{
    transform.Translate(Vector3.forward * 5 * Time.deltaTime);
}
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault Value
Vector3 translationDirection and distance to move the objectRequired
Space relativeToDefines if movement is relative to local or world spaceSpace.Self (local space)
โœ…

Key Takeaways

Use transform.Translate to move objects by adding a direction vector to their position.
Multiply movement by Time.deltaTime for smooth, frame-rate independent motion.
Specify Space.World or Space.Self to control if movement is relative to world or local axes.
transform.Translate moves relative to the object's current rotation by default.
Avoid confusing transform.Translate with directly setting transform.position for relative movement.