Search code examples
movepixi.js

How to move a Graphics object around the stage in PIXI JS?


I am trying to animate a figure and adding a health bar over it. I created the figure from a sprite (new PIXI.sprite()) and the health bar from a graphics object (new PIXI.Graphics()).

I am able to move the sprite by setting its X,Y coordinates, but when I do the same with the Graphics object it is always displaced, it looks like its origin is the current position of the sprite. See the following picture. The health bar should be above the figure.

enter image description here

var app = new PIXI.Application(windowWidth, windowHeight, {backgroundColor: 0x1099bb});
var prey = new PIXI.Sprite(texturePath);
var healthBar = new PIXI.Graphics();
healthBar.beginFill(0x00BB00);
healthBar.lineStyle(1, 0x000000);
healthBar.drawRect(prey.x - spriteLength, prey.y - spriteLength, spriteLength, 5);
prey.energyBar = healthBar;

app.stage.addChild(prey);
app.stage.addChild(healthBar);

prey.energyBar.position.set(prey.x,prey.y);

How can I set the position of the health bar to be right above the figure?


Solution

  • A better way to do this would be to have the healthbar as a child of the prey Sprite itself. As an example (bits you've already solved missed out)

    var prey = new PIXI.Sprite( texturePath );
    var heathbar = new PIXI.Graphics();
    healthbar.y = -100;
    
    prey.addChild( healthbar );
    app.stage.addChild( prey );
    

    Now, that the health bar is a child of your prey Sprite, when you move the prey Sprite around, the healthbar will move with it (which I presume is what you would want in your situation).