I am trying unitys new 2d and i am trying to get my player to look at the enemy. I used transform.lookat but when i do the player turns sideways and disappears. The camera is locked on the x and y axises as default. How can i make my player look at the enemy rotating on the Z axis? I am using the sprite gameObject not a regular mesh Thanks. C#
This question coming up a lot with the new 2D stuff, and there seems to be as many non-working solutions posted as working ones. Assuming a sprite, an Orthographic camera, and with the ‘forward’ of your object facing ‘right’ when the rotation is (0,0,0), this will work:
Vector3 dir = enemy.position - transform.position;
float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
I think this is the best one…
insert the tag of the object that u want to look at
and play with the offset
public string Tag;
public float offset;
private Transform target;
private Vector3 targetPos;
private Vector3 thisPos;
private float angle;
void Start ()
{
target = GameObject.FindGameObjectWithTag(Tag).GetComponent<Transform>();
}
void LateUpdate()
{
targetPos = target.position;
thisPos = transform.position;
targetPos.x = targetPos.x - thisPos.x;
targetPos.y = targetPos.y - thisPos.y;
angle = Mathf.Atan2(targetPos.y, targetPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
}
public Transform target;
void Update()
{
transform.rotation=Quaternion.FromToRotation(transform.position,-target.position);
}