2

I made a simple "animation" with PhysicsJS, where I have this body:

                balon = Physics.body('circle', {
                    x: 50,
                    y: random(20, 350),
                    vx: 0.45,
                    angle: random(0,360),
                    angularVelocity:-0.005,
                    radius: 60,
                    mass: 1,
                    fixed: true
                });
                    balon.view = new Image();
                    balon.view.src = 'ballon.png';

All works good but I need to add a shadow for the "ball", this means that I need to use two images the "ballon.png" and the second image (the shadow) need to be fixed over the first image (don't rotate with the body).

Any idea hot to do this ?

Thank you in advance !

Russo
  • 301
  • 3
  • 12

1 Answers1

3

If you need one of the images to have a different behavior, you'll need to handle the rendering yourself.

You can add another rendering layer for shadows. If you store the shadow image inside body.shadow, then you can do something like this.

var shd = renderer.addLayer('shadows');
var bodies = [balon];
// draw the provided shadow view
shd.drawShadow = function( body, view ){
    var pos = body.state.pos
        ,v = body.state.vel
        ,t = renderer._interpolateTime || 0
        ,x
        ,y
        ,aabb
        ,ctx = shd.ctx;
        ;

    // interpolate positions
    x = pos.x + v.x * t;
    y = pos.y + + v.y * t;

    ctx.save();
    ctx.translate( x, y );
    ctx.drawImage(view, -view.width/2, -view.height/2, view.width, view.height);
    ctx.restore();
}
shd.render = function(){
    var body;

    for (var i = 0, l = bodies.length; i < l; i++){
        body = bodies[ i ];
        if ( body.shadow ){
            shd.drawShadow( body, body.shadow );
        }
    }
};
Jasper
  • 1,193
  • 1
  • 9
  • 14
  • Thank you for the answer! I'm sorry I'm a noob with this. Where I should add this ? Because I have a function that creates the bodies randomly. But if I put the code inside I have an error message: "Uncaught Layer "shadows" already added. " – Russo Jun 12 '14 at 22:11
  • You only need to create the shadow layer once. Just make sure the bodies variable contains all the bodies added that need shadows. Put this outside your body creation function – Jasper Jun 17 '14 at 15:52