Jump to content

Move all sprites in a group at once


Muyiwa
 Share

Recommended Posts

Quick Q:

 

If I have a group, i.e.:

var enemies = game.add.group();

And then I populate them like so:

for 1 - 30 // lazy haha{// Create a star inside the stars groupvar enemy = enemies.create(randomX, randomY, 'grr');// keep track of current x and y vals for clash checking (done before this code)currentXVals[i] = randomX;currentYVals[i] = randomY;// gravityenemy.body.gravity.y = 50;// Random bounce valueenemy.body.bounce.y = 0.7 + Math.random() * 0.2; // tutorial code ;)enemy.body.bounce.x = 0.7 + Math.random() * 0.2;star.body.velocity.x = 0; // trying to establish a velocity?star.body.collideWorldBounds = true;}

The above just spawns them in random locations, doesn't seem to be a problem as the spawning works perfectly.

 

I also have a player object. What I want to do is when I move a player, I want the enemy to mimick the exact move, so an algorithm could be something like:

if (we press left on the keyboard){        player.velocity.x = -150 //moves the player left?        move each enemy in the enemies group to the left as well // this is what I can't implement properly}

My game dev background is an XNA one so it would be similar to using a foreach loop to go through each element in the group of enemies and update the X and Y values when the left key is pressed.

 

Thanks :D

 

 

 

 

 

Link to comment
Share on other sites

You've two options:

 

You can move the Group itself by just changing its x/y coordinates. This will have the effect of adjusting all children too, but it may not be what you require, as children x/y coordinates are relative to the parent (the Group), not the screen. Even so, I'd try this out first.

 

Secondly you can use the methods like Group.addAll, here's the code so you can see what it does:

/*** Adds the amount to the given property on all children in this Group.* Group.addAll('x', 10) will add 10 to the child.x value.** @method Phaser.Group#addAll* @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.* @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.* @param {boolean} checkAlive - If true the property will only be changed if the child is alive.* @param {boolean} checkVisible - If true the property will only be changed if the child is visible.*/Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) {    this.setAll(property, amount, checkAlive, checkVisible, 1);};
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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