0
\$\begingroup\$

So i've been trying to make an enemy follow my player on Unity2d using transform.LookAt.
While it does follow the player, It also rotates the enemy as well in 3D but my sprite is made for 2d so the sprite just vanishes. Any ideas?

//follows player
transform.position = Vector2.MoveTowards(transform.position, target.position, speedEnemy * Time.deltaTime);

//make enemy look towards player
transform.LookAt(target);
\$\endgroup\$
1
0
\$\begingroup\$

This should work:

using UnityEngine;

 public class Enemy : MonoBehaviour
 {

 public Transform target;
 public float speed = 3f;

 private void Update()
 {
     if (Vector3.Distance(transform.position, target.position) > 1f)
     {
         MoveTowards(target.position);
         RotateTowards(target.position);
     }
 }

 private void MoveTowards(Vector2 target)
 {
     transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
 }

 private void RotateTowards(Vector2 target)
 {        
     Vector2 direction = (target - (Vector2)transform.position).normalized;
     var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; 
     var offset = 90f;
     transform.rotation = Quaternion.Euler(Vector3.forward * (angle + offset));
 }
 }

enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ Thank you! I more or less get the code that you posted after some research except for direction.Normalize(); what does it exactly do? I didn't really get the explanation in the documentation. \$\endgroup\$ – lover of the feet Apr 13 '20 at 6:23
  • \$\begingroup\$ @loverofthefeet It returns just the direction of the vector, rather than the vector multiplied by its length. We don't need length, just direction, so we normalize the vector. Sometimes you get unexpected results when you don't normalize the vector, sometimes you don't. It depends on what's being done. \$\endgroup\$ – Sean Carey Apr 13 '20 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.