bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } CCSprite* sp1 = CCSprite::create("Icon.png"); sp1->setPosition(ccp(200, 160)); addChild(sp1, 0, 1); CCSprite* sp2 = CCSprite::create("Icon.png"); sp2->setPosition(ccp(300, 160)); addChild(sp2, 0, 2); CCLabelTTF* label = CCLabelTTF::create("没有发生碰撞", "Thonburi",24); label->setPosition(ccp(240, 280)); addChild(label, 1, 3); return true; } bool HelloWorld::ccTouchBegan(cocos2d::CCTouch *touch, cocos2d::CCEvent *event) { CCSprite* sp1 = (CCSprite*)getChildByTag(1); sp1->setPosition(touch->getLocation()); return true; } void HelloWorld::ccTouchMoved(cocos2d::CCTouch *touch, cocos2d::CCEvent *event) { CCSprite* sp1 = (CCSprite*) getChildByTag(1); sp1->setPosition(touch->getLocation()); CCSprite* sp2 = (CCSprite*)getChildByTag(2); CCLabelTTF* label = (CCLabelTTF*) getChildByTag(3); //碰撞检测,矩形碰撞 if((sp1->boundingBox()).intersectsRect(sp2->boundingBox())) { label->setString("碰撞啦"); }else { label->setString("还是没有碰撞"); } } void HelloWorld::ccTouchEnded(cocos2d::CCTouch *touch, cocos2d::CCEvent *event) { } void HelloWorld::onEnter() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true); CCLayer::onEnter(); } void HelloWorld::onExit() { CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); CCLayer::onExit(); }