Jump to content

Create multiple sprites from one texture


Hazzr
 Share

Recommended Posts

Hi,

I am making a platformer game with pixijs. I am creating the platforms with a container and multiple sprites, but it is messy and inconvient for me to create a sprite for every block of the platform.

Here is what I am doing now:

var platform = new Container();

crate1 = new Sprite(resources.tiles.textures["boxCrate.png"]);
crate1.position.set(0, 0);
platform.addChild(crate1);

crate2 = new Sprite(resources.tiles.textures["boxCrate.png"]);
crate2.position.set(1 * 128, 0);
platform.addChild(crate2);

crate3 = new Sprite(resources.tiles.textures["boxCrate.png"]);
crate3.position.set(2 * 128, 0);
platform.addChild(crate3);

crate4 = new Sprite(resources.tiles.textures["boxCrate.png"]);
crate4.position.set(3 * 128, 0);
platform.addChild(crate4);

stage.addChild(platform);

Hopefully you get what I mean... anyway to speed this up?

Link to comment
Share on other sites

  • 4 years later...

Here is a function that uses the same logic and allows you to pass in an array of sprites and return a container. I am using a sprite sheet. 

const createContainerofAllSprites = (arrayofSprites: Sprite[]): Container => {
  var platform = new Container();;

  for (var i = 0; i < arrayofSprites.length; ++i) {
    //Each Sprite
    let sprite = arrayofSprites[i]
    
    // Create a new sprite by passing in the old one. This is needed incase you have two or more of the same sprite in the array
    var newSprite = new Sprite(sprite.texture);
    
    spr.position.set(i * 128, 0);
    platform.addChild(newSprite)

}
const app = new Application({})


//The sprites you are going to pass into the function. Loop logic works here too, keeping it simple .
const sprite1: Sprite = new Sprite(Texture.from("pic_01.png"))
const sprite2: Sprite = new Sprite(Texture.from("pic_02.png"))

const allSprites: Sprite[] = [ sprite1, sprite2 ] 

const containerwithAllSprites: Container = createContainerofAllSprites(allSprites)
app.stage.addChild(containerwithAllSprites)

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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