1

我试图弄清楚如何使用 PhysicsJS。我首先只是想简单地弄清楚如何改变让我们说点击时对象的位置或速度......但我就是想不通!

( function()
{
    var viewWidth = 500,
    viewHeight = 300,
    renderer = Physics.renderer( 'canvas', 
    {
        el: 'viewport',
        width: viewWidth,
        height: viewHeight,
        meta: false,
        styles: 
        {
            'circle' : 
            {
                strokeStyle: 'hsla(60, 37%, 17%, 1)',
                lineWidth: 1,
                fillStyle: 'hsla(60, 37%, 57%, 0.8)',
                angleIndicator: 'hsla(60, 37%, 17%, 0.4)'
            }
        }
    }),
    viewportBounds = Physics.aabb(0, 0, viewWidth, viewHeight),
    constraint = {
        aabb: viewportBounds,
        restitution: 0.99,
        cof: 0.99
    },
    ballOptions = {
        x: 100,         // x-coordinate
        y: 100,         // y-coordinate
        vx: 0.0,    // velocity in x-direction
        vy: 0.0,    // velocity in y-direction
        radius: 20
    },
    gravity = Physics.behavior('constant-acceleration', 
    {
        acc: { x : 0, y: 0.0004 } 
    }),
    ball = Physics.body('circle', ballOptions );

    Physics( function( world )
    {

    // add the renderer
    world.add( renderer );
    // add circle
    world.add( ball );

    // subscribe to ticker to advance the simulation
    Physics.util.ticker.subscribe(function( time, dt )
    {
        world.step( time );
    });

    // on every step...
    world.subscribe( 'step', function()
    {
        world.render();
    });

    world.subscribe( 'collisions:detected', function( $collision )
    {

    });

    var onElementClick = function()
    {
        // do something
    };

    document.getElementById( 'viewport' ).addEventListener( 'click', onElementClick, false );

    // Lets GO!
    Physics.util.ticker.start();

});
})();

非常感谢任何帮助

4

1 回答 1

4

一种选择是采用已创建但从未添加到世界的重力,并在单击时执行此操作。

world.add(gravity);

从您询问改变物体的位置或速度的意义上来说,这是作弊。为此,请修改球的状态。请参阅 Bodies 上的文档,特别是属性。你可以设置 state.pos 来移动它。要让它运动,请设置速度:

ball.state.vel.set(.1,-.5); // move right and upward

设置速度的jsfiddle

于 2014-02-22T19:49:40.837 回答