1、 创建一个精灵sprite;
2、一个触摸事件 listener ,设置listener的onTouchBegan,onTouchMoved,onTouchEnded;
3、将sprite 和 listener关联起来。
Sprite* sprite1 = Sprite::create("pk.png"); this->addChild(sprite1,0); sprite1->setPosition(ccp(300,400)); sprite1->setTag(1); Sprite* sprite2 = Sprite::create("pk.png"); this->addChild(sprite2,0); sprite2->setPosition(ccp(200,400)); sprite2->setTag(0); Sprite* sprite3 = Sprite::create("pk.png"); this->addChild(sprite3,0); sprite3->setPosition(ccp(400,400)); sprite3->setTag(0); auto listener1 = EventListenerTouchOneByOne::create();//创建一个触摸监听 listener1->setSwallowTouches(true); //设置是否想下传递触摸 //通过 lambda 表达式 直接实现触摸事件的回掉方法 listener1->onTouchBegan = [](Touch* touch,Event* event){ auto target = static_cast<Sprite*>(event->getCurrentTarget()); Point locationInNode = target->convertToNodeSpace(touch->getLocation()); Size s = target->getContentSize(); Rect rect = Rect(0,s.width,s.height); if (rect.containsPoint(locationInNode)) { log("sprite began... x = %f,y = %f",locationInNode.x,locationInNode.y); target->setOpacity(180); return true; } return false; }; listener1->onTouchMoved = [](Touch* touch,Event* event){ auto target = static_cast<Sprite*>(event->getCurrentTarget()); target->setPosition(target->getPosition() + touch->getDelta()); }; listener1->onTouchEnded = [=](Touch* touch,Event* event){ auto target = static_cast<Sprite*>(event->getCurrentTarget()); log("sprite onTouchesEnded.. "); target->setOpacity(255); }; _eventDispatcher->addEventListenerWithSceneGraPHPriority(listener1,sprite1); _eventDispatcher->addEventListenerWithSceneGraPHPriority(listener1->clone(),sprite2); _eventDispatcher->addEventListenerWithSceneGraPHPriority(listener1->clone(),sprite3);如果想实现多个精灵拖动,使用clone方法 原文链接:https://www.f2er.com/cocos2dx/341436.html