我在HTML5中编写2D游戏,Canvas,我需要解决一个圆 - 矩形碰撞,这是我的代码:
function Rect(x, y, w, h) {
this.x = x; // Top x
this.y = y; // Top y
this.w = w; // Width
this.h = h; // Height
}
function Circle(x, y, r) {
this.x = x; // Center x
this.y = y; // Center y
this.vx = 0; // Velocity x
this.vy = 0; // Velocity y
this.r = r; // Radius
this.d = 0.7 // Density
}
var ball = new Circle(200, 300, 20);
var box = new Rect(150, 400, 200, 60);
var friction = 0.8, gravity = 0.5;
这是游戏中的主循环,如你所见,盒子是静止物体,而球是移动物体:
function update() {
ball.vx *= friction;
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
if (collides(ball, box)) {
resolve(ball, box); // Here is the problem, to resolve the collision.
}
render();
requestAnimationFrame(update);
}
我该如何解决这个问题?是否有任何类型的算法,如果是这样,我如何将其实现到我的代码中?没有wiki链接或libs,请求!:
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
function collides(c, b) { // circle, box
var cx = c.x.clamp(r.x, r.x + r.w);
var cy = c.y.clamp(r.y, r.y + r.h);
var dx = c.x - cx;
var dy = c.y - cy;
var d2 = dx * dx + dy * dy;
return d2 < (c.r * c.r);
}
function resolve(c, b) {
// ???
}
// Or just one function?
function collision(c, b) {
// ???
}
编辑:找到如何检测碰撞但我仍然需要知道如何解决它。