简体   繁体   中英

Detecting Collision With Object in Loop

Is there a way to detect collision with an object created using a while loop?

I'm repeating an image across the screen using a while loop:

this.spikeX = 0;
while (this.spikeX < this.world._width) {
    this.spike = this.add.sprite(this.spikeX, 0, 'spikes');
    this.physics.arcade.enable(this.spike);
    this.gameObjects.push(this.spike);
    this.spikeX += (this.spike.width * 0.75);
}

I have a collision function:

collision: function(obj1, obj2) {
    if (obj1.body.x < obj2.body.x + obj2.body.width &&
        obj1.body.x + obj1.body.width > obj2.body.x &&
        obj1.body.y < obj2.body.y + obj2.body.height &&
        obj1.body.height + obj1.body.y > obj2.body.y) {
            return true;
    }
},

if(this.collision(this.player, this.spike)) {
    console.log('spike');
}

When I call this function in the update function it doesn't detect collision but works when I just create a single spike outside the while loop.

That's probably because you have only one this.spike. If you have multiple sprites, you need to put them into a group, and create them like this:

spike_group = game.add.group();
spike = spikes.create(spikeX, 0, 'spikes');

Then you check collision for each spike inside spike_group and a player.

And, why don't you use arcade collision like this:

// inside update function
physics.arcade.collide(player, spike_group , overlap_spikes, this);

// out of update function
function overlap_spikes()
{
    console.log("touch spike");
}

Note: These examples does not use 'this' keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM