Customizing touches in the sprite class

In this section, we will create a custom touch sprite class to show that touch functions can also be used to add to individual classes and not only to scene nodes. This will also let us move the objects that were previously added to the scene.

Getting ready

As we will need to create a custom class, we need to create a new class and call it SSCustomSprite.

How to do it…

First, we will add the following in the header file:

#import "CCSprite.h"
#import "cocos2d.h"

@interface SSCustomSprite :CCSprite

@end

Then, in the interface file, we will add the following:

#import "SSCustomSprite.h"

@implementation SSCustomSprite

- (void)onEnter {

  [superonEnter];
  self.userInteractionEnabled = true;
}

- (void)onExit {

  [superonExit];
  self.userInteractionEnabled = false;
}


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

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

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

@end

We added the onEnter and onExit functions to the class and enabled and disabled under interaction on the file.

We also added the touchBegan and touchMoved functions. We didn't do anything in the touchBegan function, but in the touchMoved function, we got the touch location from the parent and assigned it to the object itself. As we created a CCSprite subclass, we wanted the touch location in whichever class the instance of this class is added, so in this case, we called the touch location of the parent class instead of the current class.

How it works…

Now, we will go back to MainScene.h; here we will import the custom sprite class we created and change the hero class name to our custom sprite class instead of CCSprite:

#import <CoreMotion/CoreMotion.h>
#import "SSCustomSprite.h"

@interface MainScene :CCNode{

SSCustomSprite *hero;

In the implementation file, we will change the touchBegan and touchMoved functions, as follows:

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

  CCLOG(@"TOUCHES BEGAN");

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

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

  CCLOG(@"TOUCHES MOVED");

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

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

  CCLOG(@"TOUCHES ENDED");

  hero = nil;
}
- (void)touchCancelled:(CCTouch *)touch withEvent:(CCTouchEvent *)event{

  hero = nil;
}

Now, if you click on any object already added to the scene and drag it around, the object will move around along with the finger.

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

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