For a pentamino type game I want to add a cursor with blocks.
The player can select different blocks, so the cursor block will change, with different shapes and different ammount of tiles. So there are blocks that consist of 5 tiles, but also with 4 tiles or 3 tiles.
The current block has to move all together, all tiles at once, as a whole. So I use a Phaser.Container
.
The tiles are added to the container and then move the container with the mouse cursor.
The problem is every time I call blockGetNext
there are more sprites added. So the existing tiles from the previous block and all tiles from the next block.
Now I know you can call removeAll(true), but this will either remove the sprites from the container (and leave them in memory?) or destroy all sprites. During the game it will then constantly be creating and destroying sprites, which doesn’t seem very efficient(?).
So my question is, what is the best way to remove sprites from a container
, or is it better to recycle/re-use the same sprites, but just on different positions?
// call once at start of game
blockInit: function() {
console.log("blockInit");
// container for block sprites
this._cntBlock = this.add.container(0, 0);
this.blockGetNext(0);
this._cntBlock.x = 100;
this._cntBlock.y = 100;
//this.blockGetNext();
},
// call every time player wants to change block
blockGetNext: function(idx) {
console.log("blockGetNext");
// all shapes
var shapes = [
[ [1,0,0,0,0], // [][] = S shape
[1,1,0,0,0], // []
[1,0,0,0,0], // [][]
[0,0,0,0,0],
[0,0,0,0,0] ],
[ [0,0,0,1,1], // [][][] = T shape
[0,0,0,0,1], // []
[0,0,0,0,1], // []
[0,0,0,0,0],
[0,0,0,0,0] ],
[ [0,0,1,0,0], // []
[0,0,1,1,0], // [][] =tetris block
[0,0,1,0,0], // []
[0,0,0,0,0],
[0,0,0,0,0] ]
];
// select the shape
var shape = shapes[idx];
// add tiles to build block
for (var y = 0; y < shape.length; y++) {
for (var x = 0; x < shape[y].length; x++) {
var b = shape[y][x];
if (b == 1) {
// position
var xpos = x * TILE_SIZE;
var ypos = y * TILE_SIZE;
// add sprite to group
var spr = this.add.sprite(xpos, ypos, "sprites", "coin_white");
// remember grid position for later when rotating
spr.setData("xgrid", x);
spr.setData("ygrid", y);
this._cntBlock.add(spr);
};
};
};
},
// place block in puzzle
examineBlock: function() {
console.log("examineBlock");
for (var i=0; i < this._cntBlock.list.length; i++) {
var xgrid = this._cntBlock.list[i].getData("xgrid");
var xgrid = this._cntBlock.list[i].getData("ygrid");
console.log("examineBlock x,y = " + xpos + ", " + ypos);
// check grid positions etc.
};
},