Setting swipe event to a sprite

200 views Asked by At

I'm assinging a swipe event to a cocos2dx sprite but basically the problem is the event is assigned to the whole screen. I want it to be assigned only to the single sprite. Here is my code:

rect = Sprite::create();
rect->setTextureRect(Rect(0, 0, 180, 80));

// ekranın y ekseninde ortası | visibleSize.height / 2 + origin.y
rect->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height + 80));
auto grad = LayerGradient::create(Color4B(255, 255, 38, 255), Color4B(199, 173, 68, 255));
grad->changeHeight(rect->getContentSize().height);
grad->changeWidth(rect->getContentSize().width);
//grad->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
//grad->addChild(rect);

rect->addChild(grad);
this->addChild(rect);


auto listener = EventListenerTouchOneByOne::create();

listener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(GameScene::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(GameScene::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(GameScene::onTouchCancelled, this);

listener->setSwallowTouches(true);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, rect);
1

There are 1 answers

0
Striker On

A touch event is usually triggered when the player touches the screen. The best way to implement a listener on a sprite would be by sub-classing it: http://www.cocos2d-x.org/wiki/How_To_Subclass_Sprite_And_Add_Event_Listeners

You can later check the collision of the touch within the sprite listener event (on Touch Began) and then perform your function