4

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;
})();
4

2 回答 2

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
于 2013-11-14T17:52:10.943 回答
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;
})(); 
于 2013-11-10T00:43:13.947 回答