How do you make enemies move toward you?


#1

Hey, I’m trying to make a game that requires enemies move toward you to try hurting you and i need help with having the enemies move toward my character/player.


#2

Hey @I_lik_turtles,

Here’s a project that demos one way to make this work.

follower-Jan22-2019-10.34PM.wick (2.9 KB)

This is the code I place on the “enemy”.

// One way to follow a character. 
function update() {
    // How far are we? 
    xDistance = this.x - hero.x; 
    yDistance = this.y - hero.y; 
    
    // A number between 0 and 1
    speed = .02; 
    
    // Move a little closer to the hero by "removing" distance
    this.x -= xDistance * speed; 
    this.y -= yDistance * speed; 
}

Basically, we need to slowly change our enemy’s x and y position toward our main character. This code does have a flaw, in that the enemy will slow down once it gets closer to the main character, since there is less distance between the enemy and the main character.

Let me know if this helps!


#3

thank you this will very much help me! :smile:


#4

just made a new post regarding help for a wait script!


#5

help accepted! good job!