Search code examples
javascripthtmlcanvasphysicsjs

How to use two images in physicsjs


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 !


Solution

  • 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 );
            }
        }
    };