- Home /
Lookat player
Hi there
I am making a 2D top down game. I am now trying to make the enemies always rotate to face the player. Ive just tried this:
using UnityEngine;
using System.Collections;
public class ZLookatPlayer : MonoBehaviour {
public Transform Player;
void Update () {
// Rotate the camera every frame so it keeps looking at the Player
transform.LookAt(Player);
}
}
With no success. It seems like the zombies rotates on all 3 axis, making them invisible when vivewing from a 2d perspective. I guess the lookat is only for 3d... Anyway, could anybody help me with a usefull method to make this work in a 2d top-down environment? I have viewed atleast 4 similar threads with no successs.
Thank you in advance!
Answer by Hellium · Jul 14, 2015 at 08:06 AM
Try with this :
Vector3 direction = Player.position - transform.position ;
// Prevent weird behavior if the player and enemy are very close to each other
if( direction.magnitude > 0.1f )
{
// If the target is at the right side of the enemy
if( Vector3.Dot( Vector3.right, direction ) > 0 )
transform.rotation = Quaternion.LookRotation( direction ) * Quaternion.Euler( 0, -90, 0 ) ;
// If the target is at the left side of the enemy, prevent the sprite to flip
else
transform.rotation = Quaternion.LookRotation( direction ) * Quaternion.Euler( 0, 90, 180 ) ;
}
This makes them rotate but in a very wierd way. They rotate very slow and randomly "flips" but thanks anyway, its a step on the way :D
Can you use Quaternions at 2D space? Its physically impossible.
@Tageos : I am sorry, I am not familiar with 2D games at all. If I have time, I will try to take a deeper look.
@EmreBgdy : In Unity, you are not restricted to a 2D space, even if you make 2D games. Your sprites just belongs to the (xy) plane to make them fully visible and not distorded, but you still work in a 3D space in fact. Thus, you can use the Quaternions.
@Hellium thank you for taking your time, it would be so much better if they just had a 2D equivalent of the lookat function...
I have found the solution, take a look :
using UnityEngine;
using System.Collections;
public class LookAt : $$anonymous$$onoBehaviour {
public Transform target ;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 direction = target.position - transform.position ;
if( direction.magnitude > 0.1f )
{
if( Vector3.Dot( Vector3.right, direction ) > 0 )
transform.rotation = Quaternion.LookRotation( direction ) * Quaternion.Euler( 0, -90, 0 ) ;
else
transform.rotation = Quaternion.LookRotation( direction ) * Quaternion.Euler( 0, 90, 180 ) ;
}
}
}
I edited the answer so that you can copy-paste it.
Answer by barbe63 · Jul 14, 2015 at 10:20 AM
Not familiar with 2D too but try this:
transform.LookAt(new Vector3(Player.position.x, transform.position.y, Player.position.z));
Not entirely sure about the axis being right...
this made them rotate around the y/x axis making them appear invisible.