- Home /
How to make top-down objects rotate to face another?
As the title says, I am making a top down style game, and am having difficulty getting enemies to rotate to face the player properly. I found this code from another post, and have tried tweaking the values of Vector3.RotateTowards, but I can't quite get the result I'm looking for.
public Transform target;
public float speed;
void Update() {
Vector3 targetDir = target.position transform.position;
float step = speed * Time.deltaTime;
float moveStep = moveSpeed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);
transform.rotation = Quaternion.LookRotation(newDir);
With this code, the enemy will rotate on all 3 axes, but will eventually become 'invisible'. How do I isolate just the 'z' axis?
Thanks!
edit: I know this question has been brought up before, but I've looked through all the solutions I've found and haven't been able to find one that suits my needs.
Answer by robertbu · Feb 14, 2014 at 12:56 AM
You say 'top-down'. Top-down to me is a game played on the XZ plane with the camera looking down the 'Y' axis. You say 'isolate just the 'z' axis. This implies a game where the camera is looking towards positive 'z'...perhaps a 2D game. So if this is true, you can do an immediate rotation by:
Vector3 dir = target.position - transform.position;
float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
If you want to rotate over time as implied by the RotateTowards, you can do use Quaternion.RotateTowards():
#pragma strict
var target : Transform;
var speed = 90.0;
private var qTo : Quaternion;
function Update () {
var lookPos = target.position - transform.position;
var angle : float = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
qTo = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTo, speed * Time.deltaTime);
}