1.当点击一个对象时,需要做的碰撞检测
var listener = cc.EventListener.create({
event:cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches:true, //吞没事件
onTouchBegan: function (touch,event) {
if(that.IsReachTarget) return;
var target = event.getCurrentTarget(); //当前点击的对象
var pos = touch.getLocation(); //获取当前全局点击点坐标
var s = target.getContentSize(); //获取点击对象的尺寸
var rect = cc.rect(0, 0, s.width, s.height); //对象的框型区域
var localPoint = target.convertToNodeSpace(pos); //转换为本地坐标 (把点击的全局坐标点转换为对应对象的局域坐标)
if (cc.rectContainsPoint(rect, localPoint)) { //检测点和对象的碰撞
//cc.log(target.g_sherd_name);
target.zIndex = SHRED_NUM*SHRED_NUM;
return true
}else{
return false
}
2.上面的例子,也可以吧对象的坐标转为世界坐标
var target = event.getCurrentTarget(); //当前点击的对象
var pos = touch.getLocation(); //获取当前全局点击点坐标
var s = target.getContentSize(); //获取点击对象的尺寸
var localPoint = target.convertToWorldSpace(cc.p(0,0)); //转换为全局坐标(对象的局域坐标点转换为世界坐标)
var rect = cc.rect(localPoint.x,localPoint.y, s.width, s.height); //对象的框型区域
if (cc.rectContainsPoint(rect,pos)) { //检测碰撞
cc.log(target.g_sherd_name);
return true
}else{
return false
}
3.两个框体之间的碰撞检测,就拿我曾经做过的飞机游戏为例:
var rect1 = myPlane.getBoundingBox(); //获得我放飞机的框体尺寸
var rect2 = enemyPlane.getBoundingBox(); //获取敌方飞机的框体尺寸
if(cc.rectIntersectsRect(rect1, rect2)){ //检测两个框体的碰撞
this.removeFromParent(true);
myplane.beHit();
}