Rotate a gameobject to player position ?

Hi

I am creating a 2D game and I have a prefab enemy, this enemy is a cannon. I want rotate this cannon when player change position.

The cannon should always rotate to player position

How can I do this ?

I’m trying this.

public class CanonBehavior : MonoBehaviour {

    private Transform player;
    
	// Use this for initialization
	void Start () {
	    player = GameObject.FindGameObjectWithTag("AirPlane").transform;
	}
	
	// Update is called once per frame
	void Update () {
	    float distance = Vector2.Distance(player.position, transform.position);
        if(distance < 10){
            Vector2 v2 = player.position - transform.position;
            v2.Normalize();
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(v2), 1f * Time.deltaTime);
        }
	}
}

For 2D, construct your cannon so that the front faces right when the rotation is (0,0,0). Then you ca do:

 if(distance < 10){
         Vector2 v2 = player.position - transform.position;
         angle = Mathf.Atan2(v2.y, v2.x) * Mathf.Rad2Deg;
         Quaternion Qto = Mathf.AngleAxis(angle, Vector3.forward);
         transform.rotation = Quaternion.Slerp(transform.rotation, qTo, 1f * Time.deltaTime);
     }

I solved the problem

I did this.

// Update is called once per frame
	void Update () {
	    float distance = Vector2.Distance(player.position, transform.position);
        if(distance < 10){
            Vector2 dir = player.position - transform.position;
            float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
            Quaternion qto = Quaternion.AngleAxis(angle, Vector3.forward);
            Quaternion qto2 = Quaternion.Euler(qto.eulerAngles.x,
                                                qto.eulerAngles.y,
                                                qto.eulerAngles.z -90);

            transform.rotation = Quaternion.Slerp(transform.rotation, qto2, 5f * Time.deltaTime);       
        }
	}