![](/img/trans.png)
[英]HTML5 Canvas 2D Frameworks focusing on collision detection and physics
[英]2D collision detection on html5 canvas
我正在尝试复制一个称为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/
也! 如果您可以向我介绍可以教我这些知识的优质画布教程,我将不胜感激! 我似乎只找到了另一种语言,无论如何对我有帮助,但是偶尔看到画布碰撞检测和解决教程将是非常不错的...
在.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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.