- Home /
The question is answered, right answer was accepted
Rotating enemy object to face the player when moving
Hello i have a small problem.
I am trying to write my own Ai logic what I am trying to do is to make the enemy to face the player when he is moving towards him.
I have tried using the transform.LookAt function but it makes the enemy to move away from the player.
I don't know how to make the enemy face the player. Can anybody help me ?
     public float movementSpeed = 6f;
     public float distanceFromTarget = 3f;
 
     Transform player;
 
     // Use this for initialization
     void Start ()
     {
         player = GameObject.FindGameObjectWithTag("Player").transform;
     }
     
     // Update is called once per frame
     void Update ()
     {
         
         Vector3 distance = player.position - transform.position;
         Vector3 direction = distance.normalized;
         Vector3 velocity = direction * movementSpeed;
 
         
 
         float distanceToTarget = distance.magnitude;
 
         if(distanceToTarget > distanceFromTarget)
         {
             
             transform.Translate(velocity * Time.deltaTime);
            
             
         }
 
         
         
     }
 }
Answer by ironZinc · Feb 19, 2018 at 08:56 AM
There is a chance that your enemy model may be oriented wrong inside the object, so forward for the enemy gameobject may look like backward model-wise. If this is your issue, you can try to add an empty gameobject under your enemy object and make it a parent of your model. Then, rotate this object 180 degrees.
Answer by · Oct 06, 2017 at 04:36 PM
Your enemy Forward direction is probably wrong. Try:
 transform.LookAt(2 * transform.position - player.position);
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                