[SOLVED] Move a sprite while screen is currently touched

Good day,

How can I move a sprite while the screen is currently touched?

onTouchBegan lets me move the sprite every new touch only.
onTouchMoved lets me move the sprite only if the user swipe his finger.

Thanks.

In onTouchBegan, schedule a function call to a function that will move your sprite. In onTouchEnded, unschedule that function.

What you might be looking for are actions, which allow you to animate certain properties (like a node’s position or color) over a finite period of time. For example you can trigger an action when the user touches the screen if you want.

I have tried doing this inside the onTouchBegan:
this->schedule(CC_SCHEDULE_SELECTOR(GameScene::walkRight));

to run this:
void GameScene::walkRight (float dt)
{
auto action = RepeatForever::create(MoveBy::create(5, Vec2(8, 0)));
mysprite->runAction(action);
}

but it does not stop the action in onTouchEnded:
void GameScene::onTouchEnded(const std::vector<cocos2d::Touch > &touches, cocos2d::Event event)
{
this->unschedule(schedule_selector(GameScene::walkRight));
}

*Also when I change the ‘5’ to ‘1’ of auto action = RepeatForever::create(MoveBy::create(5, Vec2(8, 0)));
my sprite does not move.

*Do I have to put some coded in onTouchMoved also?

Just run your action in onTouchBegan and stop the action in onTouchEnded.

How? by unschedule?

The easiest way is to use Sprite’s stopAllActions function. Just call it like mysprite->stopAllActions();

If you sprite is running multiple actions and you only want to stop one of the actions, you need to use stopAction, but this will require keeping a reference to the action. (runAction returns a reference to the action, so just assign it to a variable declared in your header.)

1 Like

Thanks :smile:

By your help guys here is the code for future reference:

Header File: Game.h

void onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);
void onTouchEnded(Touch* touch, cocos2d::Event *event);
void walkRight(float dt);

cocos2d::Sprite* mysprite;

Implementation File: Game.cpp

bool Game::init()
{
//code snippet

auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);

listener->onTouchBegan = CC_CALLBACK_2(Game::onTouchBegan, this);
listener->onTouchEnded = CC_CALLBACK_2(Game::onTouchEnded, this);

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

}

void Game::walkRight (float dt)
{
auto action = RepeatForever::create(MoveBy::create(MOVESPEED, Vec2(MOVE_BY, 0)));
mysprite->runAction(action);
}

void Game::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event)
{
this->schedule(CC_SCHEDULE_SELECTOR(Game::walkRight));
}

void Game::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event)
{
this->unschedule(schedule_selector(Game::walkRight));
mysprite->stopAllActions();
}

1 Like