没有引力的小型JavaScript Box2D程序无论如何都会移动...为什么?

时间:2012-10-08 20:09:28

标签: javascript box2d

我有一个小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;

据我所知,这些代码都没有引入力量,所以如果有人知道为什么球的坐标会发生变化,请告诉我,所以我可以把它变成有用的东西而不是混淆的东西= )

1 个答案:

答案 0 :(得分:0)

事实证明我的代码创建了一个固体对象作为游戏世界,这意味着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);
  [....]
}