Ribs
Ribs

Reputation: 1505

Physicsjs - Using sprite sheet to assign parts of one bitmap to multiple bodies

I'd like to create a sequence of letters that can be broken apart. Ideally I'd only load one spritesheet to generate the views of the different letters. I am assigning images to the view of bodies as follows:

// letter is a physicsjs rectangle body
letter.view = new Image();
letter.view.src = 'someImage.jpg';

I'd like to now if there is a way to change the background position of a bitmap assigned to the view of a physicsjs body.

Upvotes: 1

Views: 453

Answers (2)

Ribs
Ribs

Reputation: 1505

I attempted to use the pixi renderer but kept getting an error:

"undefined is not a function evaluating PIXI.Stage"

So I ended up writing my own solution. In the canvas renderer, in the drawBody() method, I changed:

ctx.drawImage(view, -view.width/2, -view.height/2 );

to:

if( body.backgroundPosX != undefined || body.backgroundPosY != undefined )
{
    body.backgroundPosX = body.backgroundPosX != undefined ? body.backgroundPosX : 0;
    body.backgroundPosY = body.backgroundPosY != undefined ? body.backgroundPosY : 0;
    ctx.drawImage( view, body.backgroundPosX, body.backgroundPosY, body.width, body.height, -body.width/2, -body.height/2, body.width, body.height );
}
else
{
   ctx.drawImage(view, -view.width/2, -view.height/2 );
}

which allowed me to pass backgroundPosX and/or backgroundPosY as an option when creating a body, and use that offset and a few other different params to position the sprite sheet within a masked area.

The conditional presumes that it must not be a sprite sheet if no backgroundPosX/Y is present. Its there because for some reason this only worked when assigning an image to a body, but not with a body containing only a shape. When a shape only body was created, it kept coming out 2 pixels short of what the assigned width should be, but was perfect when using a body with an image.

This seems like it would be good core functionality, if the discrepancy above was worked out.

Great job on the library too! Looking forward to seeing what else happens with it!

Upvotes: 0

Jasper
Jasper

Reputation: 1193

Try using the PIXI renderer for this.

You can then use pixi textures and sprites to do want.

// set the base sprite
var base = PIXI.Texture.fromImage( spriteURL );
// get the first "frame"
var first = new PIXI.Texture( base, new PIXI.Rectangle( 0, 0, 100, 100 ) );

// set the view on the body
body.view = new PIXI.Sprite( first );
body.view.anchor.set(0.5, 0.5);

Here's an example: http://codepen.io/wellcaffeinated/pen/ByKapK

Using this sprite: http://www.xojo3d.com/images/sprite1.png

PIXI.js texture docs: http://www.goodboydigital.com/pixijs/docs/classes/Texture.html

Upvotes: 1

Related Questions