Jump to content

Make enemy bounce back on collision?


Recommended Posts

I'm having trouble making enemies bounce back a bit after colliding with the player so that they don't just sit there relentlessly attacking. I had written this messy code:

function collideEnemy(player, enemy) {

	player.immune = true;

	// Knocks back enemy after colliding
	enemy.follow = false;
	if(enemy.body.touching.left) {
		enemy.body.velocity.x = 256;
	} else if (enemy.body.touching.right) {
		enemy.body.velocity.x = -256;
	} else if (enemy.body.touching.up) {
		enemy.body.velocity.y = 256;	
	} else if (enemy.body.touching.down) {
		enemy.body.velocity.y = -256;

	// Makes the player immune for 1 second and then resets it and the enemy following movement
	game.time.events.add(Phaser.Timer.SECOND * 0.5, function() {
		player.immune = false;
		enemy.follow = true;
	}, this);

...which worked for a single enemy, but stopped functioning when I made my monsters into a group. Does anyone have a better solution for this, or at least a way to make it work for grouped enemies? Here's my collision code:

game.physics.arcade.overlap(player, monsters, collideEnemy, null, this);


Link to comment
Share on other sites

On 3/23/2018 at 6:40 PM, samme said:

I don't see anything in particular wrong with it.

Set a breakpoint in collideEnemy to see what it's doing or whether it's being called at all.

Thanks for the reply! It definitely is as there's code I stripped out of my post to kill the enemy, which works. And I know that the touching code is working as I popped in a console.log to be sure. It's a mystery...

Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...