0
votes

I am trying to make a game with Phaser Arcade Physics where you control a sprite and try to avoid objects with arrow keys. However, I have problems making collision happen between those objects and the sprite.

My code: https://jsfiddle.net/o445dt44/

It is specifically at line 69 in the JSFiddle, I would like you to take a look.

//game.physics.arcade.collide(sprite, enemy, enemy2, enemy3);

This should usually do the job of the collision, however it is not.

Any help is greatly appreciated. Thanks!

1

1 Answers

2
votes

FYI for the future, your JSFiddle is missing an external reference to Phaser. There's a CDN version you can include at https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.2/phaser.min.js, for example.

Second, you're actually not using the collide function correctly. Per the documentation it's actually collide(object1, object2, collideCallback, processCallback, callbackContext).

I've created a forked version that setups collisions properly. In particular the following changes were made:

The enemies need to be setup at the same level as the sprite.

var enemy;
var enemy2;
var enemy3;

Next, in your update, given how you have things setup, you need to setup collisions between all objects individually:

game.physics.arcade.collide(sprite, enemy);
game.physics.arcade.collide(sprite, enemy2);
game.physics.arcade.collide(sprite, enemy3);
game.physics.arcade.collide(enemy, enemy2);
game.physics.arcade.collide(enemy, enemy3);
game.physics.arcade.collide(enemy2, enemy3);

The alternative, and better way to do this, would be to setup your enemies as a group and then have your sprite collide with the group.

There's an official Sprite Vs Group example that covers this. If you want the enemies to collide, you could then setup the group to collide with itself.

game.physics.arcade.collide(enemies, enemies);