如何在physicsjs中使用两个图像

How to use two images in physicsjs

本文关键字:两个 图像 physicsjs      更新时间:2023-09-26

我用PhysicsJS制作了一个简单的"动画",其中我有这样的主体:

                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';

所有工作都很好,但我需要为"球"添加阴影,这意味着我需要使用两个图像"ballon.png"和第二个图像(阴影)需要固定在第一个图像上(不要随身体旋转)。

你知道怎么做吗?

提前感谢!

如果您需要其中一个图像具有不同的行为,则需要自己处理渲染。

你可以为阴影添加另一个渲染层。如果您将阴影图像存储在body.shadow中,那么您可以这样做。

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