我试图复制一款名为haxball的游戏,这是一款非常简单且基本的2D足球游戏。但是我在碰撞检测方面遇到了麻烦,我不想使用像Box2d这样的引擎,因为它对我想要的东西有点过分,而且我只是为了练习游戏,我是初学者。
我可以检查碰撞是否发生,但我无法正确解决。我循环穿过所有物体并检查它们是否与球发生碰撞然后,如果它们是,我将球放在"边界"对象,以便它停止"内部"另一个。 问题出现在这里,因为如果球同时与圆圈和边缘碰撞,它将留在边缘内或圆圈内。
这是圆的碰撞解码以及边缘的检测和解析:
this.resolveCollisionCircle = function(circle) {
var nv = circle.pos.sub(this.pos);
nv = nv.setMag(circle.radius + this.radius).add(circle.pos);
this.pos = nv;
// I'll try to add later the bounce effect
}
this.edgeCollision = function() {
if(this.pos.x-this.radius < 0) {
this.pos.x = this.radius;
this.velocity = this.velocity.mult(new Vector(-1, 1));
}
else if(this.pos.x+this.radius > Width) {
this.velocity = this.velocity.mult(new Vector(-1, 1));
}
if(this.pos.y-this.radius < 0) {
this.pos.y = this.radius;
this.velocity = this.velocity.mult(new Vector(1, -1));
}
else if(this.pos.y+this.radius > Height) {
console.log('baixo')
this.velocity = this.velocity.mult(new Vector(1, -1));
}
}
球相应地移动到速度矢量,在这种情况下,它以(-4,0)
开始演示错误:http://antoniomc.0fees.us/
另外!如果你能指出我可以教我这些东西的好画布教程,我将不胜感激!我似乎只找到了另一种帮助我的语言,但偶尔看一下画布碰撞检测和分辨率教程会很高兴...
答案 0 :(得分:0)
在.resolveCollisionCircle()
中,存储旧位置,更改位置,然后恢复到旧位置,如果新位置位于画布之外,则完全停止球。
this.resolveCollisionCircle = function(circle) {
//previous position
var prevPos = this.pos;
//set new position
var nv = circle.pos.sub(this.pos);
nv = nv.setMag(circle.radius + this.radius).add(circle.pos);
this.pos = nv;
//change back if out of canvas
if ((this.pos.x-this.radius < 0) || (this.pos.x+this.radius > Width) || (this.pos.y-this.radius < 0) || (this.pos.y+this.radius > Height)) {
this.pos = prevPos;
this.velocity = this.acceleration = new Vector(0, 0);
}
}