How can I drag and place the object in a fixed position?It is like putting plants in plants and zombies
To drag something, use the onTouchMoved event callback. More info here.
How you decide to place an object in a fixed position is really up to you, and has nothing to do with the game engine. It’s game-specific logic that you need to design and implement.
Use this code:
bool YourScene::init() {
auto touch_listener = EventTouchOneByOne::create();
auto touching_func = [this](Touch* touch, Event* event) -> bool {
if(sprite_to_drag->getBoundingBox()->containsPoint(touch->getLocation()) {
dragTouch(touch->getLocation().x, touch->getLocation().y);
}
return true;
};
touch_listener->onTouchBegan = touching_func;
touch_listener->onTouchMoved = touching_func;
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touch_listener, this);
}
void YourScene::dragTouch(float x, float y) {
sprite_to_drag->setPosition(x, y);
}
Note:
This implementation will work for slow drags, but if the touch delta is more than the your sprites radius it shouldn’t work.
I do something similar:
sprite->setPosition(cocos2d::Vec2(sprite->getPosition() + touch->getDelta()));