How to make enemy AI move side to side on platform

I’m trying to make a simple enemy AI where the enemy (animated sprite) moves side to side on the ground but gets faster over time, capping at a max speed .

I’ve followed the official “get started with your first game” tutorial for the platformer and I’m stuck on how to make my enemy move on its own (without player input).

Something like

if (enemy.x < LEFT && enemy.body.velocity.x < 0) {
  enemy.setVelocityX(speed);
  if (speed < MAX) speed += INC;
} else if (enemy.x > RIGHT && enemy.body.velocity.x > 0) {
  enemy.setVelocityX(-speed);
  if (speed < MAX) speed += INC;
}
1 Like

Thanks for the logic samme! That should be able to do it.

A few questions, would I put this code inside the update () or the create()?

Also, how can I get an animation to play on the enemy while it moves? I am currently using the following method to give the enemy animations. I need them to play whenever the enemy moves though:

“this.anims.create({
key: ‘left’,
frames: this.anims.generateFrameNumbers(‘dude’, { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});”

Put it in update() because it needs to run each frame.

Animations can be something like

if (enemy.body.velocity.x < 0) {
  enemy.anims.play('left', true);
} else if (enemy.body.velocity.x > 0) {
  enemy.anims.play('right', true);
} else {
  player.anims.play('turn');
}
1 Like

Ok perfect thanks.

One thing I’ve noticed though is that your solution doesn’t work at 60 fps but works fine at 30.

Doesn’t work how?

Basically the enemy won’t move. I ended up simplifying the logic by just saying (after giving the enemy some initial velocity):

function update() { 
//START ENEMY LOGIC
if (baddie.x == RIGHT){
  baddie.setVelocityX(-baddiespeed);
  if (baddiespeed < MAXSPEED){
    baddiespeed += baddiespeedstep;
  } 
}
else if (baddie.x == LEFT){
  baddie.setVelocityX(baddiespeed);
  if (baddiespeed < MAXSPEED){
    baddiespeed += baddiespeedstep;
  } 
}

}

Mine doesn’t prevent the enemy from stopping, but if you want that you can do

if (enemy.x < LEFT && enemy.body.velocity.x <= 0) {
  enemy.setVelocityX(speed); // etc.
} else if (enemy.x > RIGHT && enemy.body.velocity.x >= 0) {
  enemy.setVelocityX(-speed); // etc.
}
1 Like