官术网_书友最值得收藏!

Creating a custom sprite class

We just considered how to add a sprite to a scene; however, in the future, you may want a separate sprite class so that you can add your own behaviors to the class. In this section, we will discuss how to create our own custom sprite class by extending the base CCSprite class.

Getting ready

Let's take a look at how to create a custom sprite class so that it can have its own movement and update the function later.

For this, we will have to create new files.

  1. Go to File | New | File. Under iOS | Source, select Cocoa Touch Class. Click on Next.
  2. Next, we will give it a class name. We will select CCSprite as Subclass of and Objective–C as Language. Click on Next.
  3. Next, we will click on Create to add the files to your projects.

How to do it…

Now that the files are created, let's make some changes to them so that it can take a string as the filename and create the sprite from the file.

In the Hero.h file, we make the following changes:

#import "CCSprite.h"

@interface Hero :CCSprite{

  CGSizewinSize;
}

-(id)initWithFilename:(NSString *) filename;

@end

Now, we will change the Hero.m file as follows:

#import "Hero.h"

@implementation Hero

-(id)initWithFilename:(NSString *)filename
{
  if (self = [super initWithImageNamed:filename]) {

  }

  return self;
}
@end

How it works…

To create an instance of the newly created custom sprite class, we will go to MainScene.h, import the Hero.h file, and create a new instance of the Hero type called hero with the following code:

#import "Hero.h"

@interface MainScene :CCNode{

  CGSizewinSize;
 Hero* hero;

}

In the MainScene.m file, we will add the following code right after the place we added rtSprite:

hero = [[Hero alloc]initWithFilename:@"hero.png"];
hero.position = CGPointMake(center.x - winSize.width/4, winSize.height/2);
[selfaddChild:hero];

Here, we initialized hero with the hero.png file. In the Resources folder, we have to import the hero-ipad.png and hero-ipadhd.png files into the project in a similar way to how we added the Bg image files.

We will place hero at one-quarter the width of the screen, to the left of the center of the screen, and place it at half the height of the screen. Lastly, we will add the hero object to the scene.

Let's next take a look at how to animate the hero object.

主站蜘蛛池模板: 红河县| 宜宾县| 弋阳县| 广丰县| 襄城县| 连城县| 洪泽县| 卢龙县| 庆城县| 鹤山市| 池州市| 盱眙县| 宜州市| 安吉县| 宁陕县| 渑池县| 察隅县| 南丰县| 德清县| 江门市| 云浮市| 黄大仙区| 易门县| 马鞍山市| 江口县| 运城市| 石渠县| 哈巴河县| 茌平县| 木里| 苏尼特右旗| 黄陵县| 邢台市| 区。| 昭苏县| 阿瓦提县| 和龙市| 高安市| 长汀县| 婺源县| 鄂托克旗|