点和圆的碰撞检测:
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和p2的x坐标之间,并且p的y坐标是否在p1和p2的y坐标之间
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;
}
}
矩形和矩形的碰撞检测:
1.在水平方向上,判断两个矩形中点x坐标的距离是否小于两个矩形宽度的一半之和
2.在垂直方向上,判断两个矩形中点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;
}
}
1、cc.rectIntersectsRect(ra,rb) 判断两个矩形是否相交,若相交,返回true
用例:
var rectA = cc.rect(0,0,5,10);
var rectB = cc.rect(4,9,5,10);
var r = cc.rectIntersectsRect(rectA, rectB);
if(!r) throw "Fail rectIntersectsRect 1”;
2、cc.rectContainsPoint(rect,point) 判断某个矩形中是否包含某个点,若包含,返回true
3、cc.pointEqualToPoint(point1,point2) 判断两个点是否相等,相等返回true
4、cc.rectEqualToRect(rect1,rect2)判断两个矩形是否相等
5、cc._rectEqualToZero(rect)判断该矩形是否为0矩阵
6、cc.rectOverlapsRect(rectA,rectB)判断两个矩形是否部分重叠
7、cc.rectIntersection(rectA,rectB)返回两个矩形重叠部分
8、cc.rectUnion(rectA,rectB)返回包含这两个矩形的最小矩形