October 16, 2011
If you want to have an object turn automatically towards a target then you have to find out in which direction to turn. The usual angle function just returns the smallest angle between the current heading and the heading towards the target but not which way around.
Vector3 lTarget = transform.InverseTransformPoint(target.position);
targetDistance = lTarget.magnitude;
targetAngle = Mathf.Atan2(lTarget.x, lTarget.z) * Mathf.Rad2Deg;
- This calculates the position in relation to the current objects local coordinate system.
- It then calculates the distance (because you’ll need it anyway).
- Finally it calculates the angle in radians and then converts it to degrees, just for good measure.