O'Reilly logo

Cocos2d Cross-Platform Game Development Cookbook - Second Edition by Siddharth Shekar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating objects with touchBegan

Wherever we place a finger on the screen, we want to add an instance of the hero sprite.

Getting ready

If you have already imported the hero image into the project, then we are good to go.

How to do it…

In the touchBegan function, we will add the following code:

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

  CCLOG(@"TOUCHES BEGAN");

  CGPointtouchLocation = [touch locationInNode:self];

  CCSprite* hero = 
    [CCSpritespriteWithImageNamed:@"hero.png"];
  [selfaddChild:hero];
  hero.position = touchLocation;
}

How it works…

We will first get the location of the touch using the locationInNode function and pass in the current class. This will get the touch location in the current scene. Then, as usual, we ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required