Raimi:
float angle = 0;
Vector3 relative = transform.InverseTransformPoint(target.position);
angle = Mathf.Atan2(relative.x, relative.y)*Mathf.Rad2Deg;
transform.Rotate(0,0, -angle);
Raimi options works. But it does instantly rotate, not smoothly rotate. Another solution I found is the following, very similar to Raimi’s one:
SCRIPT
// Assign in inspector the gameobject you want to look at
public GameObject targetGameObject
// Rotation modifier makes a correction on the rotation axis and allows us to adjust the look
// at from axis the one we want to be (just try it and you will understand what it means easily)
float rotationModifier = 90;
// Call the function in fixedUpdate
private void FixedUpdate()
{
ManualLookAt2D();
}
private void ManualLookAt2D()
{
// Calculate the difference between our gameObject and the desired target
Vector3 vectorToTarget = targetGameObject.transform.position - transform.position;
// This functions serves as conversion from 3D space to 2D space
// Forward makes the look at axis being the x axis
// Returns the angle in radians whose Tan is y/x.
// Return value is the angle between the x-axis and a 2D vector starting at zero and terminating at (x,y).
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg - rotationModifier;
// Sets the transform’s current rotation to a new rotation that rotates “angle” degrees around
// the - y-axis(Vector3.up ), z-axis (Vector3.forward), x-axis (Vector.right)
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
// Smoothly rotates from our gameObject current rotation to the desired rotation to look
// at the target
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed);
}