In my project I have to make an object follow the mouse pointer. With this script it works well the problem is when I turn the object in negative on the X axis that gives problems. How do I solve?
void Update()
{
Vector2 mousePos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
Vector2 posScreen = Camera.main.WorldToViewportPoint(gunPivot.position);
float angle = Angle(posScreen, mousePos);
gunPivot.rotation = Quaternion.Euler(new Vector3(0, 0, angle + 180f));
}
float Angle(Vector2 a, Vector2 b)
{
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
The simplest way
gunPivot.transform.LookAt(mousePos);
A more elaborate way
// both directions are in world space
Vector3 dir1 = gunPivot.transform.forward;
Vector3 dir2 = (mousePos - gunPivot.transform.position).normalized;
Quaternion q = Quaternion.FromToRotation(dir1, dir2);
gunPivot.transform.localRotation *= q; // local transformation
the elaborate way for when XZ are the actual coordinates in 2D
void someMethod() {
// mousePos is assumed to be Vector2 as well
Vector2 dir1 = toXZ(gunPivot.transform.forward);
Vector2 dir2 = (mousePos - toXZ(gunPivot.transform.position)).normalized;
Quaternion q = Quaternion.FromToRotation(toXYZ(dir1), toXYZ(dir2));
gunPivot.transform.localRotation *= q;
}
Vector2 toXZ(Vector3 p) => new Vector2(p.x, p.z);
Vector3 toXYZ(Vector2 p) => new Vector3(p.x, 0f, p.y);
there are even more elaborate ways, but if you’re a beginner, I’m sure LookAt will suffice.