2014-02-06 67 views
1

我想弄清楚如何使用PhysicsJS。我首先只是想簡單地弄清楚如何改變可以說一個對象的位置或速度點擊...但我不能弄明白!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(); 

}); 
})(); 

任何幫助非常感謝

+0

說什麼@ScottSPerry。你也可以施加一些力量。使用.applyForce()。 – slacktracer

回答

4

一種選擇是採取已創建,但從來沒有加入到這個世界,做那個的onclick的嚴重性。

world.add(gravity); 

這就是你提到的改變物體位置或速度的問題。要做到這一點,請修改球的狀態。 See the docs on Bodies,特別是屬性。你可以設置state.pos來移動它。爲了把它在運動,集速度:

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

jsfiddle that sets velocity