简体   繁体   English

PhysicsJS-移动对象

[英]PhysicsJS - moving an object

I'm trying to figure out how to use PhysicsJS. 我试图弄清楚如何使用PhysicsJS。 I first off just want to simply figure out how to change lets say a position or a speed of an object on click... but I just cant figure it out! 首先,我只想简单地弄清楚如何更改,让我们说一下单击对象的位置或速度...但是我无法弄清楚!

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

});
})();

any help much appreciated 任何帮助非常感谢

One option is to take the gravity that was created but never added to the world and do that onclick. 一种选择是采用已创建但从未添加到世界上的引力,然后单击onclick。

world.add(gravity);

That's cheating in the sense that you asked about changing the position or speed of an object. 从您询问要更改对象的位置或速度的意义上讲,这就是作弊。 To do that, modify the state of the ball. 为此,请修改球的状态。 See the docs on Bodies , specifically the properties. 请参阅有关实体的文档 ,特别是属性。 You can set state.pos to move it. 您可以设置state.pos来移动它。 To put it in motion, set the velocity: 要使其运动,请设置速度:

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

jsfiddle that sets velocity 设置速度的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM