Quantcast
Viewing all articles
Browse latest Browse all 10

[Cocos2d] CCSpriteクラスのサブクラスを作る

Image may be NSFW.
Clik here to view.


cocos2dで、CCSpriteクラスのサブクラスを作る方法です。

例として、CCSpriteを継承したDogクラスを作成してみます。

Dog.h
1
2
3
4
5
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface Dog : CCSprite
+(id)dog;
@end

Dog.m
1
2
3
4
5
6
@implementation Dog
+(id)dog
{
    return [[[super alloc] initWithFile:@"dog.png"] autorelease];
}
@end

これでDogのインスタンスが生成できます。

SampleLayer.m
1
2
3
4
5
6
7
8
9
#import "SampleLayer.h"
#import "Dog.h"
@implementation SampleLayer
(...)
Dog *dog = [Dog dog];
dog.anchorPoint = CGPointZero;
[self addChild:dog];
(...)
@end

Image may be NSFW.
Clik here to view.


かわいいですね。

Dogを複数生成してみます。

SampleLayer.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#import "SampleLayer.h"
#import "Dog.h"
@implementation SampleLayer
(...)
for (int y = 0; y < 5; y++) {
    for (int x = 0; x < 5; x++) {
        Dog *dog = [Dog dog];
        dog.anchorPoint = CGPointZero;
        dog.position = ccp((dog.contentSize.width * x) + (25.f * x), (dog.contentSize.height * y) + (25.f * y));
        [self addChild:dog];
    }
}
(...)
@end

Image may be NSFW.
Clik here to view.


幸せですね。

お好みでDogクラスにプロパティとかメソッドを定義してください。


環境
OS X 10.8
Xcode 4.4
cocos2d v2.0

Viewing all articles
Browse latest Browse all 10

Trending Articles