Translate, Rotate & LookAt in C# for Unity

Karuna Ketan
2 min readDec 14, 2022

--

I learned about Translate, Rotate & LookAt in Unity…

11th Programs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour
{
float _moveSpeed = 7f;
float _rotateSpeed = 200f;

void Update()
{
if (Input.GetKey(KeyCode.UpArrow))
{
gameObject.transform.Translate(new Vector2(0f, _moveSpeed) * Time.deltaTime, Space.Self);

else if (Input.GetKey(KeyCode.LeftArrow))
{
gameObject.transform.Rotate(new Vector3(0f, 0f, _rotateSpeed) * Time.deltaTime, Space.Self);
}

else if (Input.GetKey(KeyCode.RightArrow))
{
gameObject.transform.Rotate(new Vector3(0f, 0f, -_rotateSpeed) * Time.deltaTime, Space.Self);
}
}
}

From above program:

if (Input.GetKey(KeyCode.UpArrow))
{
gameObject.transform.Translate(new Vector2(0f, _moveSpeed) * Time.deltaTime, Space.Self);
}
  • If we don’t use Time.deltaTime then the gameObject will move so fast because of higher framerate…
  • If we don’t use Space.Self then as a default it is going to move around the local space of the gameObject…
  • Space.Self → It will help gameObject to move all around in the space…
else if (Input.GetKey(KeyCode.LeftArrow))
{
gameObject.transform.Rotate(new Vector3(0f, 0f, _rotateSpeed) * Time.deltaTime, Space.Self);
}
  • Rotate cuz now we need not to move the object…we need to rotate…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestScript2 : MonoBehaviour
{
[SerializeField] Transform target;
Vector2 lastRotation;

void Update()
{
Vector2 direction = target.position - transform.position;

if (lastRotation != direction)
{

transform.rotation = Quaternion.FromToRotation(Vector3.up, direction);
Debug.Log("test");
}
lastRotation = direction;
}
}

From above program:

Vector2 direction = target.position - transform.position;
  • This will say the gameObject at which it is attached to to rotate at a certain direction based on the offset…
transform.rotation = Quaternion.FromToRotation(Vector3.up, direction);
  • new Vector3(0, 1, 0) === Vector3.up/down/ left/right/ back/forward
  • Rotates the gameObject from a certain location to a new location…

That’s all…Thank you for reading😉:)

click here to follow me in LinkedIn for more updates…

click here to follow me in GitHub for more updates…

--

--

Karuna Ketan

Game Designer and Developer | Unity, Unreal Engine, Blender