Jump to content

Overlap detection between a group and child sprites


26medias
 Share

Recommended Posts

Hi,

I've spent the past 2 days stuck on something that should be very simple.

I have a sprite representing a ship.
I add 10 sprites as child using addChild around the ship.
I want to detect an overlap between any of the child sprite and the asteroids.

7jF8czZ.png

 

Here is the code used to create the ship:

this.player = this.game.add.sprite(this.options.position.x, this.options.position.y, this.options.sprite);
this.player.anchor.set(0.5);
this.player.enableBody            = true;
this.game.physics.enable(this.player);

 

Then here is how I add the "sensors" around the ship:

var sensors                = scope.game.add.physicsGroup();

for (i=0;i<=9;i++) {
    var x = (r*Math.cos(360/n*i*Math.PI/180))-(this.player.body.width/4);
    var y = (r*Math.sin(360/n*i*Math.PI/180))-(this.player.body.height/4);
    var sensor                = sensors.create(x, y, 'ship-sensor');
    sensor.name                = 'sensor-'+i;
    this.game.physics.enable(sensor);
    this.sensors.push(sensor);
}

this.player.addChild(sensors);

 

Finally, here is how the asteroids are created:
this.asteroids                = this.game.add.physicsGroup();
for (i=0;i<20;i++) {
    var asteroid            = this.asteroids.create(rand_x, rand_y, 'asteroid');
    asteroid.body.immovable    = true;
    asteroid.name            = 'asteroid-'+i;
    asteroid.body.mass        = -100;
}

 

On my update() function, I have:

this.game.physics.arcade.overlap(this.sensors, this.asteroids, function(sensor, asteroid) {
        console.log("> ", sensor, asteroid );
}, null, this);

 

 

My goal is to detect an overlap between any of the "sensors" and the asteroids so that I can feed that to a neural network to have a ship that learns to navigate on its own.

 

I tried with Arcade physics, I tried with P2 physics, and I'm about to give up and move on to another game engine at this point...

 

Anybody has a solution to that simple problem?

 

Link to comment
Share on other sites

Is "this.sensors" an array? In the update function, are you sure it has something in it? Same thing for "this.asteroids"? Is that a group or an array? Does it have stuff in it?

In your code that adds sensors, you create a physicsGroup, then push them in an array, then add them to the player. Sprites can only have one parent; since you add the sensor to the player last it will remove it from the physicsGroup. Is that what you intended? They should be okay in the array, however.

Can you make a "render" function and put "game.debug.body" calls in there to make sure the physics bodies are where you expect them to be?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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