How do you make enemies move toward you?

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.

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!

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

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

help accepted! good job!

I don’t think this works anymore. I tried using it, but nothing happened. Is there a newer method?

Change the words in bold with the names of the characters!


Keep everything the same, other than the bold words. The bolded word: ENEMY, is going to be the object that actually moves, I hope this information would help (I found the code somewhere on the forums, so I’m not the one who wrote it, but I used it for very long time)

~Hanzoh Alani

1 Like

I believe I’m the one who introduced it. Keep in mind they slow down the closer they get to you. If you don’t want that maybe do some trigonometry so that the hypotenuse (the direction the enemy moves) is the same length.

1 Like

Here’s a simpler code that is easier to breakdown:

if( NAME.x>this.x){
this.x+= 5;
swap the bolded words with the name of the player
and plug in this code inside of the update script for
the player or enemy that you’d want to move!

1 Like

thanks its the only code that worked

it does not work for me

Can you share the code maybe?

Hey folks, take a look at this AI example that I made a bit ago in this thread: How do make an ai

Might help!

past BSA 15 hi

On Scratch we call this a necropost and it is frowned upon by the community. I’m not sure if this persists in other communities, more specifically this.

and even if it wasn’t a necropost it’d still be spam

Let this topic rest in peace… I can’t handle anymore notifications…

i owe eternal gratitude to this one post because this piece of code is rather useful for camera shake and the likes