javascriptpixi.js

PixiJS character animated sprite not updating when getting reassigned


I am trying to update an animated sprite object and i have instantiated them like this:

characterMovement["walk_down"] = 
  PIXI.AnimatedSprite.fromFrames(animations["walk_down/walk_down"]);
characterMovement["walk_up"] =
  PIXI.AnimatedSprite.fromFrames(animations["walk_up/walk_up"]);
characterMovement["walk_left"] =
  PIXI.AnimatedSprite.fromFrames(animations["walk_left/walk_left"]);
characterMovement["walk_right"] =
  PIXI.AnimatedSprite.fromFrames(animations["walk_right/walk_right"]);

I then assign it like this: character = characterMovement["walk_down"];

Then I have some code that dependign on what key is pressed the animated sprite object should change like this:

if (keys['87'] && character.y > 0) {
    character= characterMovement["walk_up"];

however nothing happens when i reassign it.

I have tried just reassigning the textures like this: character.textures = characterMovement["walk_up"].textures; and that works but doesnt cycle through the animations.


Solution

  • You could try by updating the texture inside a ticker loop, as follows:

    const keys = {};
    
      window.addEventListener("keydown", (event) => {
        keys[event.key] = true;
      });
    
      window.addEventListener("keyup", (event) => {
        keys[event.key] = false;
      });
    
      app.ticker.add(() => {
        if (keys["ArrowUp"]) {
          character.texture = walkUpTexture;
          character.y -= 2;
        }
        if (keys["ArrowDown"]) {
          character.texture = walkUpTexture;
          character.y += 2;
        }
        if (keys["ArrowLeft"]) {
          character.texture = walkDownTexture;
          character.x -= 2;
        }
        if (keys["ArrowRight"]) {
          character.texture = walkDownTexture;
          character.x += 2;
        }
    
        character.rotation += 0.01;
      });
    

    Here is a working example: https://codesandbox.io/s/magical-jones-nyp48k