//GameScene.h#include "cocos2d.h"USING_NS_CC;class GameScene : public cocos2d::Layer{public: static cocos2d::Scene* createScene(); virtual bool init(); virtual bool onTouchBegan(Touch *touch, Event *unused_event); virtual void onTouchMoved(Touch *touch, Event *unused_event); bool isCircleCollision(Point pos1, float radius1, Point pos2, float radius2); CREATE_FUNC(GameScene); private: //注意不能用auto关键字 Size size; Sprite *sprite1, *sprite2; Label *label;};
//GameScene.cpp// Created by Jacedy on 14-8-11.#include "GameScene.h"USING_NS_CC;cocos2d::Scene* GameScene::createScene(){ auto scene = Scene::create(); //创建一个场景 auto layer = GameScene::create(); //创建一个图层 scene->addChild(layer); return scene;}//初始化当前的图层bool GameScene::init(){ if(!Layer::init()) //初始化父类 return false; //获取屏幕大小 size = Director::getInstance()->getVisibleSize(); //auto size = Director::getInstance()->getWinSize(); //添加一个图片精灵 sprite1 = Sprite::create("r1.png"); sprite1->setPosition(Vec2(size.width/2, size.height/2)); this->addChild(sprite1); sprite2 = Sprite::create("r2.png"); sprite2->setPosition(Vec2(size.width*0.4, size.height/2)); this->addChild(sprite2); label = Label::createWithSystemFont("No collision", "Marker Felt", 50); label->setPosition(Vec2(size.width/2, size.height*0.7)); this->addChild(label); //创建监听事件对象 auto listener = EventListenerTouchOneByOne::create(); //定义监听事件的回调函数 listener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this); listener->onTouchMoved = CC_CALLBACK_2(GameScene::onTouchMoved, this); //在事件分发器中注册 _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); return true;}bool GameScene::onTouchBegan(Touch *touch, Event *unused_event){ //获取触屏位置 Point pos = touch->getLocation(); sprite2->setPosition(pos); log("TouchBegan"); return true;}void GameScene::onTouchMoved(Touch *touch, Event *unused_event){ Point pos = touch->getLocation(); sprite2->setPosition(pos); if (isCircleCollision(sprite1->getPosition(), sprite1->getContentSize().width/2, sprite2->getPosition(), sprite2->getContentSize().width/2)) label->setString("Collision!"); else label->setString("No collision"); log("TouchMoved");}bool GameScene::isCircleCollision(Point pos1, float radius1, Point pos2, float radius2){ //运用勾股定理判断两圆是否相交 if (sqrt(pow(pos1.x - pos2.x, 2) + pow(pos1.y - pos2.y, 2)) > pow(radius1 + radius2, 2)) { return false; } return true;}
补充:其实有专门的圆形碰撞检测函数:isbong( ),可以试一下。