Why do I need to offset my aim rotation angle by 90 degrees?

I have this simple code to rotate an object (gun barrel) towards a target object (rocket ship).

The gun barrel rotates towards the ship but is always 90 degrees off. I have fixed this in my code as you can see by subtracting 90 degrees from the angle but I would like to know why it is happening and if there is a more elegant solution.

I have checked the rotation of all objects involved but that doesn't seem to change anything. Any help is much appreciated!

using UnityEngine;

public class RotateTowardsObject : MonoBehaviour {

    public float speed = 5f;        // how fast this rotates towards the target
    public Transform target;        // target to follow

    public void Update()
    {
        Vector2 direction = target.position - transform.position;                                               // direction between this position and target position
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;                                    // calculate the angle
        angle = angle - 90f;                                                                                    // ** Temporary fix(?) for rotation being +90 degrees off
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);                                     // create rotation from quaternion
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);            //  set rotation acceleration towards target
    }

Answers 1

  • As per the unit circle math, angle 0 means "pointing right". Your initial orientation is up, at 90 degrees, so that's why you need to offset by 90 degrees so that your zero is at top, and -90 at right.

    You can just keep doing this, or rotate your model to be oriented towards right by default. I find that the best practice, as then you can just swap content in and out of different systems. It's a good practice to make everything that needs to be rotated to face right in the future.


Related Questions