這里總結了一下點、圓、矩形之間的簡單碰撞檢測算法
(ps:矩形不包括旋轉狀態)
點和圓的碰撞檢測:
1.計算點和圓心的距離
2.判斷點與圓心的距離是否小於圓的半
- isCollision: function(point, circle)
- {
- //點與圓心的距離
- var distance = Math.sqrt(Math.pow(point.x - circle.x, 2) + Math.pow(point.y - circle.y, 2));
- //圓的半徑
- var radius = circle.getContentSize().width / 2;
- //如果點與圓心距離小於圓的半徑,返回true
- if(radius > distance)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
點和矩形的碰撞檢測:
1.獲得矩形的左上角坐標p1和右下角坐標p2
2.判斷點p的x坐標是否大於p1的x坐標,並且小於p2的x坐標,並且p的y坐標大於p2的y坐標,並且小於p2
- isCollision: function(point, rect)
- {
- //獲得矩形的左上角坐標p1和右下角坐標p2
- var p1 = cc.p(rect.x - rect.width/2, rect.y + rect.height/2);
- var p2 = cc.p(rect.x + rect.width/2, rect.y - rect.height/2);
- //判斷點p的x坐標是否大於p1的x坐標,並且小於p2的x坐標,並且p的y坐標大於p2的y坐標,並且小於p2的y坐標
- if(point.x > p1.x && point.x < p2.x && point.y > p2.y && point.y < p1.y)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
圓和圓的碰撞檢測:
1.計算兩圓心之間的距離
2.判斷兩圓心之間的距離是否小於兩圓的半徑之和
- isCollision: function(circle1, circle2)
- {
- //圓心與圓心的距離
- var distance = Math.sqrt(Math.pow(circle1.x - circle2.x, 2) + Math.pow(circle1.y - circle2.y, 2));
- //圓心半徑
- var r1 = circle1.getContentSize().width / 2;
- var r2 = circle2.getContentSize().width / 2;
- //如果圓心與圓心距離小於兩圓的半徑,返回true
- if(r1 + r2 > distance)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
矩形和矩形的碰撞檢測:
在水平方向上,判斷兩個矩形中點x坐標的距離是否小於兩個矩形寬度一半之和
在垂直方向上,判斷兩個矩形中點y坐標的距離是否小於兩個矩形高度一半之和
- isCollision: function(rect1, rect2)
- {
- //獲取矩形1的寬高
- var width1 = rect1.width;
- var height1 = rect1.height;
- //獲取矩形2的寬高
- var width2 = rect2.width;
- var height2 = rect2.height;
- var flag;
- if(rect1.x >= rect2.x && rect2.x <= rect1.x - width1/2 - width2/2)
- {
- flag = false;
- }
- else if(rect1.x <= rect2.x && rect2.x >= rect1.x + width1/2 + width2/2)
- {
- flag = false;
- }
- else if(rect1.y >= rect2.y && rect2.y <= rect1.y - height1/2 - height2/2)
- {
- flag = false;
- }
- else if(rect1.y <= rect2.y && rect2.y >= rect1.y + height1/2 + height2/2)
- {
- flag = false;
- }
- else
- {
- flag = true;
- }
- }
圓和矩形的碰撞檢測:
- isCollision: function(circle, rect)
- {
- //圓的半徑
- var radius = circle.width / 2;
- //圓形中心與矩形中心的相對坐標
- var x = circle.x - rect.x;
- var y = circle.y - rect.y;
- var minX = Math.min(x, rect.width/2);
- var maxX = Math.max(minX, -rect.width/2);
- var minY = Math.min(y, rect.height/2);
- var maxY = Math.max(minY, -rect.height/2);
- if((maxX - x) * (maxX - x) + (maxY - y) * (maxY - y) <= radius * radius)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
源碼下載:點擊打開鏈接