Add Enemy Movement

(Step 4/9) Learn how to make enemies move and recognize collision.

1. Go into our onUpdate function in our room.js file and add a handleCollision function that sends our characters back to the start.


code/client/src/game.js
g.handleCollision('players',  'enemy',  (player)  =>  {
	if (player.safe === false) {
		player.x =  270;
		player.y =  1980;
	}
});

2. In the onUpdate function in our room.js file we put a getAllCharacters function. (for our callback function we will set up some if else statements for the movement.


code/client/src/game.js

g.getAllCharacters('enemy', (enemy, i) => {
	if (enemy.x <= 575 && enemy.right == true) {
		g.move(enemy, 'x', .01 * i + .1);
	}
	else if (enemy.x >= 25) {
		enemy.right = false;
		g.move(enemy, 'x', -.01 * i - .1);
	}
	else {
		enemy.right = true;
	}
});


Download your zip, and upload it to blobbert.io, and you should be able to interact with enemies!


Create Enemies
Set Up Safe Zones

Need Help?

Proofread your code, check with your team and classmates, and if you’re still stuck!

Click Here for Help