horkoda Posted December 20, 2014 Share Posted December 20, 2014 I have a tile-based game with units. Each unit has a health bar above their sprite so that it is overlapping with the upper tile a bit. To achieve that I've subclassed the Sprite class and added a Graphics object as a child. When I render a newly spawn unit above the previous unit, it will hide a nice chunk of the previous unit's health bar!This makes sense since the new unit object was created AFTER, however I want the health bars to be rendered on top. For every unit. Is there a nice solution to this problem? Without me having to move the Graphic objects out from the unit objects? Link to comment Share on other sites More sharing options...
lewster32 Posted December 22, 2014 Share Posted December 22, 2014 In the end the scene graph determines the order of every sprite on the screen. You have a few options available; you could create a null sprite with the health bar and then the actual unit graphic as two children, then you can ensure the health bars is always above the unit graphic:var MyUnit = function(game, x, y) { // This extends Phaser.Sprite but has no graphic of its own, so it acts a bit like a group Phaser.Sprite.call(this, game, x, y, null); // Create the two sub-components of the unit - the health bar and the sprite this.healthBar = new HealthBar(this); this.unitSprite = game.add.sprite(x, y, "unitGraphic"); // Add the sprite first... this.addChild(unitSprite); // ... then the health bar on top. this.addChild(healthBar);}The other option would be to create a group for the health bars above all of the unit graphics, and then rather than adding the health bar as a child of the unit, you'd add it to the group and update its position via the unit's update function:var MyUnit = function(game, x, y, healthBarGroup) { this.healthBar = new HealthBar(this); healthBarGroup.add(healthBar);};MyUnit.prototype.update = function() { this.healthBar.position.copyFrom(this.position);}; horkoda 1 Link to comment Share on other sites More sharing options...
horkoda Posted December 22, 2014 Author Share Posted December 22, 2014 I will have to preallocate all the units beforehands, but I understand what you mean.Thanks! Link to comment Share on other sites More sharing options...
Recommended Posts