Jump to content

Need help with referencing to childs and changing their properties


SmartCookie
 Share

Recommended Posts

Hello, this is my first time developing a game, ever. So please bear with me :)

Currently I'm making a game where a player can shoot bullets at enemies. Each enemy has it's own healthbar, which should decrease when a bullet hits the enemy.

For now, implemented the healthbars as a spritesheet with 5 different frames and added them as children to the enemies.

function create() {
	enemies = game.add.group();
	game.physics.arcade.enable(enemies);
	enemies.physicsBodyType = Phaser.Physics.ARCADE;
	enemies.enableBody = true;
	bars = game.add.group();
	

	for (var i = 0; i < 5; i++) {
		enemy[i] = enemies.create(base1.body.x + game.rnd.integerInRange(0, 150), game.rnd.integerInRange(0, 150), 'enemy');
		enemy[i].anchor.set(0.5);
		enemy[i].health = 100;
		bar = bars.create(0, -30, 'bar'); //sticking the healthbar to the enemy
		enemy[i].addChild(bar);
		bar.anchor.setTo(0.5);
		bar.frame = 0; // first frame -> full healthbar
	}
}

function update() {
	game.physics.arcade.overlap(bullets, enemies, bulletHitsEnemy, null, this);
}

function bulletHitsEnemy(bullet, enemy) {
	bar.frame += 1; // decreasing the healthbar
	bullet.kill();
	enemy.health -= 20;
	if (enemy.health <= 0) {
		enemy.kill();
	}
}

The problem is that when I hit one of the enemies, only the healthbar of the first spawned enemy changes, all the other ones stay the same. I guess it's a problem with the bulletHitsEnemy() function, because it seems that bar.frame += 1 refers to the very first healthbar created in the enemy creation loop.

Any ideas how to fix this? Thanks.

 

 

Link to comment
Share on other sites

`bar` inside your `bulletHit` code always references the same thing, although from the snippet its not clear where that is coming from but there is a global leaking around somewhere.

I think you can access children from the `enemy` instance you pass into the function, something like `enemy.children.bar` (the exact syntax might differ, I hardly know Phaser at all) or you could do it declaratively and add a method to the enemy object that manipulates the health bar, possibly something like `enemy.setHealth()` or something. You don't really want to be manually manipulating internal object state from outside, but that is secondary to your question, it still works its just a code smell. Anyhow, sort out how you reference each health bar instance (child of enemy) and you'll get it working.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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