how to rotate an object in unity 2d code example
Example 1: how to make a object rotate towards a position in 2d unity
Vector3 targ = staticCompassTarget.transform.position;
targ.z = 0f;
Vector3 objectPos = transform.position;
targ.x = targ.x - objectPos.x;
targ.y = targ.y - objectPos.y;
float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
Example 2: unity 2d rotate towards direction
private void RotateGameObject(Vector3 target, float RotationSpeed, float offset)
{
Vector3 dir = target - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, RotationSpeed * Time.deltaTime);
}
Example 3: rotation unity script 2d
transform.eulerAngles = Vector3.forward * degrees;
transform.rotation = Quaternion.Euler(Vector3.forward * degrees);
transform.rotation = Quaternion.LookRotation(Vector3.forward, yAxisDirection);
transform.LookAt(Vector3.forward, yAxisDirection);
transform.right = xAxisDirection;
transform.up = yAxisDirection;
Example 4: rotation unity script 2d
transform.Rotate(Vector3(0, 0, 50));
transform.eulerAngles = new Vector3 (0, 0, 50);
transform.eulerAngles = Vector3.forward * 50;
Example 5: 2d rotation unity
float x;
void Update ()
{
x += Time.deltaTime * 10;
transform.rotation = Quaternion.Euler(x,0,0);
}