Hazzr Posted April 8, 2017 Share Posted April 8, 2017 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? Quote Link to comment Share on other sites More sharing options...
xerver Posted April 8, 2017 Share Posted April 8, 2017 var platform = new Container(); var texture = resources.tiles.textures["boxCrate.png"]; for (var i = 0; i < 5; ++i) { var spr = new Sprite(texture); spr.position.set(i * 128, 0); platform.addChild(spr); } stage.addChild(platform); Quote Link to comment Share on other sites More sharing options...
drzaius Posted February 14, 2022 Share Posted February 14, 2022 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) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.