Jump to content

Kill sprites out of bounds


Faizy
 Share

Recommended Posts

Hey,

 

let´s assume you have a wall going from the right to the left. The wall is stored in a group called walls. I want to kill/destroy/remove the wall from the group(groups children) as soon as it is out of bounds(on the left). I tried the following, however it didn´t work, since the children are still there and the groups.length is increasing.

function addSingleWall(x, y) {
    this.wall = game.add.sprite(x, y, 'wall')
    game.physics.arcade.enable(wall)
    //wall.body.immovable = true;
    wall.body.velocity.x = -400;
    wall.checkWorldBounds = true;
    wall.outOfBoundsKill = true;
    main.walls.add(wall)
}

Could someone help me out? :)

Link to comment
Share on other sites

Killing your sprite does not necesarilly remove it from the group. If you want to remove your wall from the group after it has left the world, then you can for example do this:

//in your add single wall
wall.events.onOutOfBounds.add(removeFromGroup, this);

//or 
wall.events.onKilled.add(removeFromGroup,this);


function removeFromGroup(wall){
  walls.remove(wall);
}

There is a difference between killing a sprite, destroying it and removing it from a group. If this wall is always the same kind object(always same properties and is added/removed often to/from the world, then it makes less sense to destroy it. Killing it would be more useful (I know this sounds very cold/cruel indeed). Here is another post that explains it a bit more:

 

Link to comment
Share on other sites

Thanks a lot!

I was wondering if something like this would be possible:

function addSingleWall(x, y) {
    this.wall = game.add.sprite(x, y, 'wall')
    game.physics.arcade.enable(wall)
    wall.body.velocity.x = -400;
    wall.checkWorldBounds = true;
    wall.events.onOutOfBounds.add(function() {wall.destroy()}, this);
    main.walls.add(wall)
}

 

It works, but it destroys the wrong wall, which makes sense.

So my question(in general) is: how do I know which wall is out of bounds, so i can set it up to get destroyed(?). IOt´s probabaly a returned value, but I cant get the grasp of it :(

 

Ah, got it from an example! Does that mean, that onOutOfBounds returns the outOfBounds object(in this case the wall) and passes it to the function which is about to get fired? I couldn´t really get that from the documentation nor the Phaser API...or am I missing something?

Link to comment
Share on other sites

You need to get the signal's argument to work on the right sprite:

wall.events.onOutOfBounds.add(function (wallOutOfBounds) { wallOutOfBounds.destroy(); });

Otherwise you're just destroying the last wall that was added.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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