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
  • \$\begingroup\$ What direction is the barrel pointing at by default? If it's not right, you need to offset it. \$\endgroup\$ – Tyyppi_77 Jun 8 '18 at 11:49
  • \$\begingroup\$ It is pointing straight up initially. I tried rotating the gun object 90 degrees in the Unity editor but it makes no difference. It will snap back to being 90 degrees off when I run the game. \$\endgroup\$ – Sam Luxton Jun 8 '18 at 11:50

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.

| improve this answer | |
  • 2
    \$\begingroup\$ Ha! I have a note in my Utilities "AngleTo" code that says "// TODO: Why does this need to be rotated pi/2" or something like that; silly in hindsight given I advocate the unit circle all the time \$\endgroup\$ – blurry Jun 8 '18 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.