- Home /
2D Top Down how to get enemy to face my player correctly?
I am making a 2D top down game, and I want my enemy to face my player and follow them. The follow part works, but the rotation is off. The enemy rotates as I move around it, but its not actually looking at me. When the enemy is horizontal to me, it's looking down, not to me. If the enemy is vertical to me, it faces to the right or to the left, not to me.
Here is my code (bottom half is to follow the player):
transform.eulerAngles = new Vector3 (0, 0, -transform.eulerAngles.z);
transform.LookAt(target.position, transform.up);
transform.Rotate(new Vector3(0,-90,0),Space.Self);//correcting the original rotation
//move towards the player
if (Vector3.Distance (transform.position, target.position) > 0.5f) {//move if distance from target is greater than 1
transform.Translate (new Vector3 (speed * Time.deltaTime, 0, 0));
dont works only with this line?
transform.LookAt(target.position);
It works with that line in 3D, I need it to only rotate the enemy on the Z Axis, thay rotates it on the y and x axis too, so the enemy goes invisible.
try this
transform.LookAt(new Vector3(transform.position.x, transform.position.y, target.position.z)
@vikingallday1 damn, it fitted like a glove! Just had to change the -90 to 90 because my sprite was facing the left. To think I almost gave up a went with a simple ball sprite.
You rock dude.
Answer by test45 · Aug 13, 2017 at 01:55 AM
Maybe the game object is looking at you!
Maybe the sprite renderer you're using is rotated on the game object incorrectly.
Create an empty and add the sprite prefab as a child, then you can rotate the sprite independently of the game object.
All I had to do was flip the image around in the sprite editor... thanks!
Answer by vardevelopment · Aug 12, 2017 at 12:20 AM
Try this: Vector3 direction = target.position - this.transform.position; float angle = Mathf.Atan2(direction.y, direction.x); this.transform.rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Rad2Deg);
I don't know why that code is all messed up because I wrote it in the insert code tab. Well anyway, Just make a new line after the semicolons. Also, I didn't really read your code too thoroughly but this is how I rotate in 2d
That makes his rotation more smoother which is good, but he still isn't facing me. He still is facing down. I've tried starting him facing at me when I start the game, but the second I start it, he the faces down.
Try changing the euler angles. If he is facing the opposite direction of what you want, do this:
Quaternion.Euler(0f,0f,angle * $$anonymous$$athf.Rad2Deg - 180f)
The -180 flips the direction. So - 90 would turn the object 1/4 a revolution.
using the -90 makes it so he spins in a circle around me, and making it 180 has him just move away from me