0

我有一个小的 Box2D 东西(使用 box2dweb.js),但是尽管将重力设置为 (0,0),并且没有对任何对象施加力/脉冲,但当我开始绘图时,我在场景中拥有的唯一动态形状会移动环形。我不知道为什么O_O

有谁知道为什么http://pomax.nihongoresources.com/downloads/temp/box2d/physics.html在点击开始后“球”会移动?

相关的代码位是:

// shortcut aliasses
var d = Box2D.Dynamics,
    v = Box2D.Common.Math,
    s = Box2D.Collision.Shapes;

var ball,
    gravity = new v.b2Vec2(0,0);
    world = new d.b2World(gravity, true);

// setup the world box
var setupWorldBox = function(worldbox) {
  var fixDef = new d.b2FixtureDef;
  fixDef.density = 0;
  fixDef.friction = 0;
  fixDef.restitution = 0;

  var bodyDef = new d.b2BodyDef;
  bodyDef.type = d.b2Body.b2_staticBody;
  bodyDef.position.x = worldbox.width/2;
  bodyDef.position.y = worldbox.height/2;
  fixDef.shape = new s.b2PolygonShape;
  fixDef.shape.SetAsBox(worldbox.width/2, worldbox.height/2);
  world.CreateBody(bodyDef).CreateFixture(fixDef);
}

// draw loop
var drawFrame = function() {
   world.Step(1/60,10,10);
   world.ClearForces();
   ball.update(); // only updates the ball's DOM element position
   requestAnimFrame(drawFrame);
};

// start the game
function start() {
  var worldParent = document.querySelector("#world");
  setupWorldBox(worldParent.getBoundingClientRect());
  ball = new Ball(worldParent, document.querySelector(".ball"), d,v,s, world);
  drawFrame();
}

对于主体,以及定义“球”的以下代码:

var Ball = function(gamediv, element, d,v,s, world) {
  var pbbox = gamediv.getBoundingClientRect();
  var bbox = element.getBoundingClientRect();
  this.el = element;
  this.width = bbox.width;
  this.height = bbox.height;

  var bodyDef = new d.b2BodyDef;
  bodyDef.type = d.b2Body.b2_dynamicBody;

  var fixDef = new d.b2FixtureDef;
  fixDef.shape = new s.b2PolygonShape;
  fixDef.shape.SetAsBox(bbox.width/2, bbox.height/2);

  bodyDef.position.x = bbox.left - pbbox.left;
  bodyDef.position.y = bbox.top - pbbox.top;

  this.b2 = world.CreateBody(bodyDef);
  this.b2.CreateFixture(fixDef);
};

Ball.prototype = {
  el: null,
  b2: null,
  width: 0, height: 0,

  // Box2D position for the ball
  center: function() { return this.b2.GetWorldCenter(); },

  // update the DOM element based on Box2D position
  update: function() {
    var c = this.center();
    this.el.style.left = c.x + "px";
    this.el.style.top = c.y + "px";
  }
};

Ball.prototype.constructor = Ball;

据我所知,这些代码都没有引入力,所以如果有人知道为什么球的坐标会改变,请告诉我,这样我就可以把它变成有用的东西而不是令人困惑的东西 =)

4

1 回答 1

1

事实证明,我的代码正在创建一个实体对象作为游戏世界,这意味着 Box2D 正在尝试执行碰撞解决,因为“球”位于另一个实体对象内。

解决方案(基于http://box2d-js.sourceforge.net但使用 box2dweb API 调用)是这样的:

// setup the world box
var setupWorldBox = function(worldbox) {
  var worldAABB = new Box2D.Collision.b2AABB;
  worldAABB.lowerBound.Set(0,0);
  worldAABB.upperBound.Set(worldbox.width, worldbox.height);
  var gravity = new b2Vec2(0, 0);
  var doSleep = true;
  var world = new b2World(worldAABB, gravity, doSleep);
  [....]
}
于 2012-10-09T01:02:08.580 回答