Sor*_*ora 2 javascript jquery html5 canvas collision-detection
我正在尝试构建一个游戏,用户应该将圆圈放在垂直条中,但我在碰撞检测功能方面遇到了麻烦.这是我的jsfiddle:http://jsfiddle.net/seekpunk/QnBhK/1/
if (collides(Bluecircle, longStand)) {
Bluecircle.y = longStand.y2;
Bluecircle.x = longStand.x2;
}
else if (collides(Bluecircle, ShortStand)) {
Bluecircle.y = ShortStand.y2;
Bluecircle.x = ShortStand.x2;
}
function collides(a, bar) {
return a.x == bar.x1 && a.y == bar.y1;
}
Run Code Online (Sandbox Code Playgroud)
[编辑修正错字和遗漏]
以下是如何对碰撞测试矩形和圆形:
演示:http://jsfiddle.net/m1erickson/n6U8D/
var circle={x:100,y:290,r:10};
var rect={x:100,y:100,w:40,h:100};
// return true if the rectangle and circle are colliding
function RectCircleColliding(circle,rect){
var distX = Math.abs(circle.x - rect.x-rect.w/2);
var distY = Math.abs(circle.y - rect.y-rect.h/2);
if (distX > (rect.w/2 + circle.r)) { return false; }
if (distY > (rect.h/2 + circle.r)) { return false; }
if (distX <= (rect.w/2)) { return true; }
if (distY <= (rect.h/2)) { return true; }
var dx=distX-rect.w/2;
var dy=distY-rect.h/2;
return (dx*dx+dy*dy<=(circle.r*circle.r));
}
Run Code Online (Sandbox Code Playgroud)
[补充说明澄清]
...这就是测试圆是否完全包含在矩形中的方法
演示:http: //jsfiddle.net/m1erickson/VhGcT/
// return true if the circle is inside the rectangle
function CircleInsideRect(circle,rect){
return(
circle.x-circle.r>rect.x &&
circle.x+circle.r<rect.x+rect.w &&
circle.y-circle.r>rect.y &&
circle.y+circle.r<rect.y+rect.h
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10969 次 |
| 最近记录: |