html5画布中的碰撞检测 [英] Collision detection in html5 canvas
问题描述
我试图建立一个游戏,用户应该将圆圈放在一个垂直条,但我碰到检测功能有困难。这是我的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;
}
修正错误和遗漏]
点击测试矩形和圆形以进行碰撞的方法如下:
演示: http://jsfiddle.net/m1erickson/n6U8D/
var circle = {x:100,y:290,r:10};
var rect = {x:100,y:100,w:40,h:100};
//如果矩形和圆形碰撞返回true
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));
}
[添加回答说明] >
...这是如何测试圆形是否完全包含在矩形中
演示: http://jsfiddle.net/m1erickson/VhGcT/
//如果圆圈在矩形内则返回true
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
)
}
I'm trying to build a game where the user should place the circle inside a vertical bar but I'm having trouble in the collision detection function. Here is my 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;
}
[ Edited to fix a typo and an omission ]
Here's how to hit-test a rectangle and a circle for collision:
Demo: 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));
}
[Added answer given clarification]
...And this is how to test if the circle is completely contained in the rectangle
Demo: 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
)
}
这篇关于html5画布中的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!