Saturday, March 21, 2015

Cocos2d-x Animating Objects with OnTouch and RunAction

cocos-2dx-touch-action-code

First of all create a new blank Cocos2d-X C++ project as shown here.
Now follow the previous tutorial(Handle Touch Input in Cocos2d-x Mobile Game) in this series. Don't add the business logic code inside HelloWorld::OnTouchEnded  callback function.

I would love to make this article stand alone by describing all the steps here but I can't do that due to lack of time. I hope it won't hurt much since the other articles are reasonably well written(at least I think so).

Now go inside HelloWorld::OnTouchEnded callback funciton in HelloWorldScene.cpp and add following to the callback

auto mainScene =  getChildByName("mainscene");
auto lblHello = mainScene ->getChildByName("lblHello");

auto vecLocationOfTouch = touch ->getLocation();

CCLOGERROR("onTouchEnded x: %f y: %f", vecLocationOfTouch.x, vecLocationOfTouch.y);


By doing this you will have a handle to the "Hello World!" label you created by following earlier tutorials.

Next we need to animate the label on touch. We will use Cocos2d-x MoveTo action in this case and supply it the vector vecLocationOfTouch.

The exact code to make the label run around the screen chasing your mouse clicks or screen taps is given below.






lblHello ->getActionManager() ->removeAllActions();

auto actMoveTo = MoveTo::create(2.0, vecLocationOfTouch);

lblHello ->runAction(actMoveTo);

You can see the removeAllActions() method call before creating the action, I'm not sure if its necessary but still I kept it there as it's not causing any harm either.

I created a moveTo action and provided it with the speed of the movement as first parameter and the end location of the animation in the second parameter.

I wish I had a decent screen capture software, I would be posting videos of final results too.

Feel free to ask questions and get in touch.

No comments:

Post a Comment

Feel free to talk back...