Problems rotating an object around the z axis to face player.

Ok, so I think this is fairly simple, but I can’t solve it and I’ve been trying for the past two days. There are many similar questions on here and I’ve looked at lots, that’s how I’ve come so close, but they aren’t quite right and I’m only a beginner.

Let me get to it.

The game is a side scrolling 2D platformer and I have the enemies fly in in a similar way to R-Type, all on a path. However at the moment the enemy object is static until I get this problem working. So, I have a game object that is the enemy, enemyType01. As a child of enemyType01 I have another game object called enemyArm. enemyArm will have a further child, a bulletSpawnPoint placed at the end, from which will spawn bullets … eventually. The difficulty I’m having is getting the enemyArm to constantly face the player. My script is in C# and is placed on the enemyArm.

So far I have tried …

    using UnityEngine;
    using System.Collections;
    
    public class enemyShotArm : MonoBehaviour
    {
           public Transform target;

           void Update
          {
                  transform.LookAt(target);
          }
    }

where I drag the player character into the public Transform in the inspector, but this rotates the arm on all axis and puts the arm behind the enemyType01 object giving this result seen looking towards the camera in the 2D mode of the scene view …

Then I tried this …

using UnityEngine;
using System.Collections;

public class enemyShotArm : MonoBehaviour
{
       public Transform target;

       void Update
       {
              transform.LookAt(transform.position + new Vector3(0,0,1), target.transform.position - transform.position );
       }

But this gave the following result …

Which is soooooo close, the enemyArm rotates as the player jumps, it’s almost perfect. Except the obvious, that it’s not quite pointing at the player.

I have also tried this inside Update…

Vector3 direction = target.position - transform.position;
float theAngle = Mathf.Atan2 (direction.x, direction.y) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis( theAngle, Vector3.forward );
transform.rotation = Quaternion.Slerp(transform.rotation, q, speed * Time.deltaTime);

However this is pretty much the inverse of the pic above. The arm is pointing down at about 7 o’clock, very very almost at the player character. A second problem with this script though is that when the player character jumps the arm rotates the wrong way, to the right.

Any help here would be greatly appreciated!

Thanks in advance.

Read about the overloaded version of LookAt. First value affects a vector, so in your case that’s Vector3.Forward. Second vector is world up. That’s where your direction to the player goes. If you don’t want y pointing toward the player, rotate by 90 degrees after looking