Unity 2d - Enemy follow player

Asked

Viewed 2,173 times

0

Well, I’m having trouble getting the enemy to follow the player, I did the code below:

public class folow : MonoBehaviour {

public Transform target;//set target from inspector instead of looking in Update
public float speed = 3f;
private Transform myTransform;


void Start()
{
    myTransform = this.GetComponent<Transform>();

}

void Update()
{

    //rotate to look at the player
    transform.LookAt(target.position);
    transform.Rotate(new Vector3(0, -90, 0), Space.Self);//correcting the original rotation



        myTransform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);



}

the problem is that it just tries to go towards the player, but fails to dodge objects and gets stuck in any obstacle

  • Of course not. After all, you did not include any code to actively avoid obstacles, just moved the enemy towards the player ignoring the scenario. If you want the enemy to find a way to the player, you will need to build a pathfinding. A response that teaches how to do this would be too broad for the format of this site. You could build a pathfinding own, but I suggest using that of Unity. Look for tutorials on NavMesh: https://www.youtube.com/watch?v=9zzMTEKif4Q Then, if you have specific questions, come back here and ask.

1 answer

1


Long live,

Basically your code is correct... Now you lack the intelligence to find the possible way to reach the target you have marked. In a simple way it has:

Both are great choices... Just take into account that in 2d only A* Pathfinding Project is compatible. I could give an example, but the necessary code is practically null, since it is already done all the scripts you need. (In both options I mentioned above)

  • 1

    Thank you so much, that’s what I was looking for, I tried using Unity’s native Navmesh but it only works in 3d

Browser other questions tagged

You are not signed in. Login or sign up in order to post.