Moving objects with touchMoved

We will now move the object once the object is created in the touchBegan function.

Getting ready

Make the hero sprite a global variable instead of local by going to the MainScene.h file and adding an instance of it, as follows:

@interface MainScene :CCNode{

CCSprite* hero;

How to do it…

In the MainScene.m file, we will modify the touchBegan and touchMoved functions, as follows:

- (void)touchBegan:(CCTouch *)touch withEvent:(CCTouchEvent *)event
{

  CCLOG(@"TOUCHES BEGAN");

  CGPointtouchLocation = [touch locationInNode:self];
  hero = [CCSpritespriteWithImageNamed:@"hero.png"];
  [selfaddChild:hero];
  hero.position = touchLocation;
}

- (void)touchMoved:(CCTouch *)touch withEvent:(CCTouchEvent *)event
{

  CCLOG(@"TOUCHES MOVED");

  CGPointtouchLocation = [touch locationInNode:self];
  hero.position = touchLocation;
}

How it works…

Whenever a touchBegan function gets called, a new instance is created, and while the finger is still pressed on the screen, no new object is created. When the finger is moved, the newly created object is also moved around.

The downside is that when the finger is released and pressed again on the screen, a new object is created, and this object is moved around instead of the previous one. Also, the previous object cannot be moved at all now.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.127.37