Box2djs, JS Physics Engine - Setting a background image for ball objects?

871 views Asked by At

Working with the Box2djs plugin here: http://www.crackin.com/dev/mms/physics/

... and all I'm trying to do is fill the ball objects with an image texture. I was hoping it was as simple as setting a css value, but I don't seem to be doing it right as none of the standard background related css rules change the balls. Using a math.random I could create 5 distinct class names to apply to each ball to create the different textured objects.

Here's an example of what it looks like now, compared to something I could make them look like using images: M&M Mock Image

This is the specific build of the physics engine I'm using this ... github.com/hrj/box2d-js ... which is using jQuery instead of Prototype.

1

There are 1 answers

1
John Carter On BEST ANSWER

I've been playing with Box2DJS a lot and think I've found everything I need to implement it for almost anything (e.g. collision detection hooks, etc). Here is a snippet of code that I wrote to integrate a box or circle image in place of a box or circle object:

if ( myBallImage )
    {
    for ( aBody = world.m_bodyList; aBody != null; aBody = aBody.m_next )
        {
        var jellyObject = aBody.GetUserData();
        if ( typeof(jellyObject) != "object" || jellyObject == null )
            continue;

        var position = aBody.GetCenterPosition();
        var angle = aBody.GetRotation();
        var mass = aBody.GetMass();
        var halfheight = 0;
        var halfwidth = 0;

        for ( aShape = aBody.GetShapeList(); aShape != null; aShape = aShape.m_next )
            {
            halfheight = aShape.GetHalfHeight();
            halfwidth = aShape.GetHalfWidth();
            }

        ctx.save();
        ctx.translate( position.x, position.y );
        ctx.rotate( angle );
        ctx.translate( -halfwidth, -halfheight );   // halfwidth, halfheight

        if ( jellyObject.shape == "MYBALL" )
            ctx.drawImage(myBallImage, 0, 0, halfwidth*2, halfheight*2 );
        else
        if ( jellyObject.shape == "MYBOX" )
            ctx.drawImage(myBoxImage, 0, 0, halfwidth*2, halfheight*2 );

        ctx.restore();
        }
    }
else
    {
    myBallImage = new Image();
    myBallImage.src = 'circle.gif';

    myBoxImage = new Image();
    myBoxImage.src = 'box.gif';
    }