- Home /
make enemy chase player in topdown 2d
so I am trying to make the enemy chase the player and this is how far I have gotten:
public Transform target;
public float speed = 2f;
private float minDistance = 1f;
private float range;
void Update ()
{
range = Vector2.Distance(transform.position, target.position);
if (range > minDistance)
{
Debug.Log(range);
transform.Translate(Vector2.MoveTowards(transform.position, target.position, range) * speed * Time.deltaTime);
}
}
But how come this guy is not moving a pixel? This script I place on the enemy prefab and the target is the player.
Hi, I'm not an expert, but you can also use Nav$$anonymous$$esh2D : AssetStore Link, and in this case, you call the specific function from Nav$$anonymous$$esh2D !
Or try with 3d vector, but with the z value at 0.
Hope this help you ;)
if I change "range" to "2" in $$anonymous$$oveTowards() the enemy will just run off in a direction and not stop, I wonder why..
is there a way to make the enemy face the character, and than walk towards him, I have been trying to figure this out, I found raycasting method that will make the enemy see the character, and tthen execute the code in this page, but I cant make him look at and walk, he just hovers motionless
Answer by Maerig · Jun 26, 2014 at 01:10 AM
This is clearer in Vector3.MoveTowards reference, but Vector2.MoveTowards returns a point in-between the current and target transforms, so you can't use it this way with Translate.
Just assign the position returned by MoveTowards :
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
I tried this and now its moving towards position 0.0 ins$$anonymous$$d of the players position.
It does work for me. Did you check the player was properly referenced as target in the inspector ? Do you have other scripts which make the enemy move ?
great, thanks very much ! you were correct ^^ I had another object referenced :S
Why does this not work if I've a prefab enemy and prefab player ? It works with prefab player and not prefab enemy ?
Answer by Lexumi_ · Nov 21, 2019 at 10:41 PM
but now the enemys go to that point where the player started but when I move the player they all go to that point not the Player how can i fix that?
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Uneven speed in 2d movement script 2 Answers
Bullet not moving from script 3 Answers
Stop Player movement when bool changes 2D 3 Answers
Emerging Gap when moving my "Snake" 1 Answer