cocos2dx 每次单点触碰后回调函数出发两次
本意是想点击一次屏幕生成一个小球,然后测试一下物理引擎。但是运行后每次点击会出现两个小球,我试着在生成小球的函数addNewSpriteAtPosition里Log了一下,发现这个函数执行了两次,但仍然找不到解决的办法。以下为截图和代码,感谢解答:
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
auto scene = Scene::createWithPhysics();
scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
auto layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
void HelloWorld::addNewSpriteAtPosition(Vec2 p) {
auto sp = Sprite::create("ball.png");
sp->setContentSize(Size(50, 50));
auto body = PhysicsBody::createCircle(sp->getContentSize().width / 2);
sp->setPhysicsBody(body);
sp->setPosition(p);
this->addChild(sp);
/*检查出这个函数执行了两次*/
int temp = rand() % 100;
CCLOG("%d\n",temp);
}
bool HelloWorld::TouchBegan(Touch *touch, Event *unused_event) {
Vec2 location = touch->getLocation();
addNewSpriteAtPosition(location);
return true;
}
bool HelloWorld::init()
{
if (!Scene::init())
{
return false;
}
Size visiableSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto body = PhysicsBody::createEdgeBox(visiableSize, PHYSICSBODY_MATERIAL_DEFAULT, 5.0f);
auto edgeNode = Node::create();
edgeNode->setPosition(Vec2(visiableSize.width / 2, visiableSize.height / 2));
edgeNode->setPhysicsBody(body);
this->addChild(edgeNode);
/*单点触控*/
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::TouchBegan, this);
listener->onTouchMoved = NULL;
listener->onTouchEnded = NULL;
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
//Close the cocos2d-x game scene and quit the application
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
/*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/
//EventCustom customEndEvent("game_scene_close_event");
//_eventDispatcher->dispatchEvent(&customEndEvent);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论