XeomDime Posted January 2, 2015 Share Posted January 2, 2015 Hi i've got a problem, with this code only one enemy moves to the ship and the others don't move.i tried a lot of times but i don't solve the problem. Can you help me? //create functionenemy = game.add.group();enemy.enableBody = true;enemy.physicsBodyType = Phaser.Physics.ARCADE;for (var i = 0; i < 16; i++) this.enemies = enemy.create(game.world.randomX, game.world.randomY, 'nemici');//update function game.physics.arcade.moveToObject(this.enemies, {x: this.nave.x, y:this.nave.y},vel_nem, this); Link to comment Share on other sites More sharing options...
XekeDeath Posted January 3, 2015 Share Posted January 3, 2015 That would be because you are only saving a reference to one enemy...this.enemies = enemy.create(game.world.randomX, game.world.randomY, 'nemici');This assigns each enemy to the same variable, thus overwriting the previously saved one, and your move to object call is only being called on one object.moveToObject is working because you are only ever calling it on one object.What it looks like you are trying to do is add each enemy to an array and then loop over that array calling moveToObject on each element.this.enemies = [];for (var i = 0; i < 16; i++) this.enemies.push(enemy.create(game.world.randomX, game.world.randomY, 'nemici'));//update functionfor (var ii = 0; ii < this.enemies.length; ii++) game.physics.arcade.moveToObject(this.enemies[ii], {x: this.nave.x, y:this.nave.y},vel_nem, this);Alternatively, if you are only ever planning on adding enemies to the group enemy, which it sounds like you are, given the name,you can use the group function forEachAlive instead of using the array method above://create functionthis.enemies = game.add.group();this.enemies.enableBody = true;this.enemies.physicsBodyType = Phaser.Physics.ARCADE;for (var i = 0; i < 16; i++) this.enemies.create(game.world.randomX, game.world.randomY, 'nemici');//update functionthis.enemies.forEachAlive(function(enemy){ game.physics.arcade.moveToObject(enemy, {x: this.nave.x, y:this.nave.y},vel_nem, this);}, this);A couple things to note in that snippet:1: The group is now being saved to a this.enemies variable. I don't know how your code is all set up, but you used this.enemies to refer to what you thought was all the enemies, so I went with that.2: The forEachAlive function takes 2+ arguments: a callback to call on each living child, the context to call that function on, and the + is any arguments to pass to the callback. So if you need to pass anything extra into the callback, add it in here: }, this, extraVar1, extraVar2, ... );and be sure to add them to the function(enemy, extraVar1, extraVar2, ... ) part...Check out the Group page in the documentation for other functions you can call on a group. XeomDime 1 Link to comment Share on other sites More sharing options...
Recommended Posts