animationpixi.js

How to dynamically change texture of PIXI.Sprite when PIXI.Sprite reaches certain position - Pixi.js?


I have a class which extends PIXI.Sprite. Here i create the sprite initially. The texture i use is a spritesheet and i create sprites from random sections of this spritesheet.png by creating random frames for the texture. There I add 10000 sprites and move them in random directions. Then I add the PIXI.Sprite class in another class which extends PIXI.ParticleContainer 10,000 times.

 createTexture() {
    this.textureWidth = 2048;
    this.rectX = () => {
        let number;
        while (number % 32 !== 0) number = Math.floor(Math.random() * this.textureWidth) + 0;
        return number;
    }
    this.rectY = () => {
        let number;
        while (number % 32 !== 0) number = Math.floor(Math.random() * 128) + 0;
        return number;
    }
    this.initialTexture = PIXI.Texture.from(this.resources[assets.images[0].src].name);
    this.rectangle = new PIXI.Rectangle(this.rectX(), this.rectY(), 32, 32);
    this.initialTexture.frame = this.rectangle;
    this.texture = new PIXI.Texture(this.initialTexture.baseTexture, this.initialTexture.frame);
    this.texture.requiresUpdate = true;
    this.texture.updateUvs();
    this.timesChangedVy = 0;
}

When a Sprite hits window borders, i call the method change texture in the class of PIXI.Sprite:

changeTexture() {
    let newTexture = PIXI.Texture.from(this.resources[assets.images[0].src].name);
    let rectangle = new PIXI.Rectangle(this.rectX(), this.rectY(), 32, 32);
    newTexture.frame = rectangle;
    // this.texture.frame = rectangle
    this.texture = newTexture;
    // this.texture = new PIXI.Texture.from(this.resources[assets.images[0].src].name)
    // this.texture._frame = rectangle
    // this.texture.orig = rectangle
    // this._texture = newTexture
    // this.texture = new PIXI.Texture(newTexture.baseTexture, rectangle)
    this.texture.update()
    this.texture.requiresUpdate = true;
    this.texture.updateUvs();
}

I tried different approaches. When i console.log the texture after changing it , i see that the frame and origins have been changed, but the new texture is not being rendered.

Does someone know where the problem lies and how i can fix it?


Solution

  • Finally, I found the reason for my sprites not updating on texture change. It is because I add them as children of Pixi.ParticleContainer, which has less functionality than Pixi.Container and does not update Uvs of children by default. THE SOLUTION IS TO SET uvs to true when creating PIXI.ParticleContainer. It looks like this: new PIXI.ParticleContainer(10000, { uvs: true }). This will solve the problem of changing textures not being updated and uvs will be uploaded and applied. https://pixijs.download/dev/docs/PIXI.ParticleContainer.html