与Chipmunk JS的碰撞失败

时间:2013-10-25 14:58:13

标签: javascript html5 game-physics chipmunk physics-engine

http://videobin.org/+70a/8wi.html

你可以看到那里发生了什么,并在这里试用一个演示:http://student.dei.uc.pt/~drgomes/carry/index.html

所以,我正在使用Chipmunk JS演示来了解它是如何工作的(参见https://github.com/josephg/Chipmunk-js)。简单的演示开始没问题,但事情开始疯狂地跳起来,到目前为止我一直试图弄清楚这一点。

var radToDeg = 180 / Math.PI;

function PlayState() {
  this.blocks = [];

  this.setup = function() {
    space.iterations = 100;
    space.gravity = new cp.Vect(0, 150);
    space.game = this;

    this.ground = space.addShape(new cp.SegmentShape(space.staticBody, new cp.v(0, 480), new cp.v(640, 480), 0));
    this.ground.setElasticity(0);
    this.ground.setFriction(1);
  };

  this.update = function() {
    space.step(this.dt);

    for (var i = 0; i < this.blocks.length; i++) {
      var block = this.blocks[i];
      block.sprite.x = block.body.p.x;
      block.sprite.y = block.body.p.y;
      block.sprite.angle = block.body.a * radToDeg;
    }

    if (isMouseDown("left")) {
      if (this.canAddBlock) {
        this.canAddBlock = false;
        this.addBlock(mouseX, mouseY);
      }
    } else {
      this.canAddBlock = true;
    }
  };

  this.draw = function() {
    clearCanvas();

    for (var i = 0; i < this.blocks.length; i++) {
      this.blocks[i].sprite.draw();
    }

    // this.ground.sprite.draw();
  };

  this.addBlock = function(x, y) {
    width = 64;
    height = 64;

    var newBlock = new Block(x, y, width, height);

    newBlock.body = space.addBody(new cp.Body(1, cp.momentForBox(1, width, height)));
    newBlock.body.setPos(new cp.v(x, y));
    newBlock.shape = space.addShape(new cp.BoxShape(newBlock.body, width, height));
    newBlock.shape.setElasticity(0);
    newBlock.shape.setFriction(1);
    this.blocks.push(newBlock);
  };
}

desiredFPS = 60;
switchState(new PlayState());

源代码非常简单,我对我创建地面的方式表示怀疑,因为我无法确切知道它实际上是什么位置。立方体似乎找到它并碰撞它。

另一个源文件是一个小块类来帮我组织事情:

Block = (function() {
  function constructor(x, y, width, height) {
    this.sprite = new Sprite("res/block.png", x, y);

    this.width = width;
    this.height = height;

  }

  constructor.prototype = {
    update: function() {

    }
  };

  return constructor;
})();

2 个答案:

答案 0 :(得分:1)

从观察行为开始,我认为它就像精灵和花栗鼠身体在同一点上旋转一样简单。我相信花栗鼠旋转是围绕质量中心。看起来精灵围绕左上角旋转。事实上,他们也可能正在从那个角落画画,这就解释了为什么他们堆叠有趣,并与底层平面相交。

我认为你需要在update函数中使用这样的东西。 (伪代码):

offset = Vector(-width/2,-height/2) 
offset.rotate_by(block.body.a)

block.sprite.x = block.body.p.x + offset.x
block.sprite.y = block.body.p.y + offset.y

答案 1 :(得分:0)

我根本不知道花栗鼠,但是玩你的演示似乎物理学根本就不对(从一开始就对我来说)。看看你的代码只是一种预感,但我认为你应该在Sprite类的Block实例上设置维度,而不是Block实例本身。

Block = (function() {
  function constructor(x, y, width, height) {
    this.sprite = new Sprite("res/block.png", x, y);

    // Do you mean to set the width and height of the sprite?
    this.sprite.width = width;
    this.sprite.height = height;

  }

  constructor.prototype = {
    update: function() {

    }
  };

  return constructor;
})();