我在上面找到了 johntraver 的答案,它回答了我所有的问题:实现物理引擎。一个小问题是它对我不起作用(0.2.0)。这是因为 contextSize 被设置为 [0,0],所以所有的墙都位于屏幕的中心。这导致我将墙设置变成一个函数并使用 Engine.nextTick() 调用它。这样,当墙壁就位时,上下文就具有大小。然后只是为了踢球,我在 Engine resize 上添加了对同一函数的另一个调用。这还要求在重新创建之前将墙壁分离,以避免创建无限数量的墙壁,而这些墙壁只会变得更小。
这是我对上述答案的调整:
/* globals define */
define(function(require, exports, module) {
'use strict';
// import dependencies
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var EventHandler = require('famous/core/EventHandler');
var View = require('famous/core/View');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var PhysicsEngine = require('famous/physics/PhysicsEngine');
var Body = require('famous/physics/bodies/Body');
var Circle = require('famous/physics/bodies/Circle');
var Wall = require('famous/physics/constraints/Wall');
function wallBounce() {
var context = Engine.createContext();
var contextSize;// = context.getSize();
var handler = new EventHandler();
var physicsEngine = new PhysicsEngine();
var ball = new Surface ({
size: [200,200],
properties: {
backgroundColor: 'red',
borderRadius: '100px'
}
})
ball.state = new StateModifier({origin:[0.5,0.5]});
ball.particle = new Circle({radius:100});
physicsEngine.addBody(ball.particle);
ball.on("click",function(){
ball.particle.setVelocity([.1,.13,0]);
});
context.add(ball.state).add(ball);
function setWalls() {
//console.log(contextSize[0]);
contextSize = context.getSize();
var leftWall = new Wall({normal : [1,0,0], distance : contextSize[0]/2.0, restitution : .5});
var rightWall = new Wall({normal : [-1,0,0], distance : contextSize[0]/2.0, restitution : .5});
var topWall = new Wall({normal : [0,1,0], distance : contextSize[1]/2.0, restitution : .5});
var bottomWall = new Wall({normal : [0,-1,0], distance : contextSize[1]/2.0, restitution : .5});
physicsEngine.detachAll();
physicsEngine.attach( leftWall, [ball.particle]);
physicsEngine.attach( rightWall, [ball.particle]);
physicsEngine.attach( topWall, [ball.particle]);
physicsEngine.attach( bottomWall,[ball.particle]);
};
Engine.nextTick(setWalls);
Engine.on('resize',setWalls);
Engine.on('prerender', function(){
ball.state.setTransform(ball.particle.getTransform())
});
};
new wallBounce();
});