Reputation: 31
I have a group where I want two types of blocks to be generated from left to right or vice versa. It is not really important; my randomization seems to work fine, but the problem is they only change if I refresh the game. But if I run it as it is, it will always be the same kind of block until I refresh. How can I fix this?
createOnebloque: function () {
this.bloquecs = ["bloqueSprite", "bloquelSprite"]; ////// Here are the 2 sprites
this.bloquesr = this.bloquecs[Math.floor(Math.random() * 2)]; /// Here I randomize, but it only works when I refresh.
this.bloque = this.game.add.group();
this.bloque.createMultiple(5, this.bloquesr);
this.bloque.setAll('anchor.x', 0.5);
this.bloque.setAll('anchor.y', 0.5);
this.bloque.setAll('outOfBoundsKill', true);
this.bloque.setAll('checkWorldBounds', true);
},
makeBloques: function () {
this.bloques = this.bloque.getFirstExists(false);
if (this.bloques) {
this.bloques.reset(1440, 1400);
this.game.physics.arcade.enable(this.bloques);
this.bloques.enableBody = true;
this.bloques.body.immovable = true;
this.bloques.body.velocity.x = -2000;
}
}
This below goes on the create funtion:
this.game.physics.arcade.collide(this.bullets, this.bloque, this.collisionBulletBloque, null, this);
Upvotes: 0
Views: 830
Reputation: 3747
Your problem comes from here:
this.bloquesr = this.bloquecs[Math.floor(Math.random() * 2)];
You pick a random key once and use it from then on.
You can maybe rewrite the first function like this:
createOnebloque: function () {
this.bloquecs = ["bloqueSprite", "bloquelSprite"];
this.bloque = this.game.add.group();
for (var i = 0; i < 5; i++) {
this.bloque.create(this.bloquecs[Math.floor(Math.random() * this.bloquecs.length]);
}
this.bloque.setAll('anchor.x', 0.5);
this.bloque.setAll('anchor.y', 0.5);
this.bloque.setAll('outOfBoundsKill', true);
this.bloque.setAll('checkWorldBounds', true);
}
I haven't tested it, but it should work.
Upvotes: 1