Javascript 与花栗鼠发生碰撞
您可以看到那里发生了什么,并在此处进行了演示: 因此,我使用花栗鼠JS演示来了解它的工作原理(请参阅)。这个简单的演示开始的很好,但是事情开始疯狂地跳跃,我一直在试图弄明白这一点,但到目前为止还没有运气Javascript 与花栗鼠发生碰撞,javascript,html,game-physics,chipmunk,physics-engine,Javascript,Html,Game Physics,Chipmunk,Physics Engine,您可以看到那里发生了什么,并在此处进行了演示: 因此,我使用花栗鼠JS演示来了解它的工作原理(请参阅)。这个简单的演示开始的很好,但是事情开始疯狂地跳跃,我一直在试图弄明白这一点,但到目前为止还没有运气 var radToDeg = 180 / Math.PI; function PlayState() { this.blocks = []; this.setup = function() { space.iterations = 100; space.gravity
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
类中的Sprite
实例上设置维度,而不是在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;
})();
从行为上看,我认为这就像精灵和花栗鼠的身体不围绕同一点旋转一样简单。我相信花栗鼠的旋转是围绕质心的。看起来精灵正在围绕左上角旋转。事实上,它们也可能是从那个角开始绘制的,这就解释了为什么它们堆叠有趣,并与底面相交 我认为在
update
函数中需要类似的东西。(伪代码):
我会启用chromes web developer工具的canvas inspector,看看发生了什么:因为我担心我无法复制这个问题。你可以把你的演示放入一个?你卡住了吗?伙计,我在这里没有发现任何问题事实上,这是一个很好的理论,我必须尝试一下,我很确定可能是这样。
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;
})();
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