【问题标题】:Adding a subclass of CCSprite to a scene将 CCSprite 的子类添加到场景中
【发布时间】:2012-02-24 16:44:06
【问题描述】:

我最近决定对我的精灵进行子类化,但是对于如何将它们添加到场景中我有点不知所措。目前,我已经创建了我的 CCSprite 子类,使用 New File>Cocos2d>CCNode>Subclass of... CCSprite。然后,我在 Sprite.h 文件中制作了我的精灵:

@interface Mos : CCSprite {
    CCSprite *mos;
}

完成后,我在 Sprite.m 中编写如下代码:

@implementation Mos

-(id) init
{
    if( (self=[super init])) {

        mos = [CCSprite spriteWithFile:@"sprite_mos.png"];

    }
    return self;
}

我想知道的是如何将这个精灵添加到我的游戏场景中。

【问题讨论】:

    标签: ios xcode cocos2d-iphone subclass ccsprite


    【解决方案1】:

    这里是如何正确继承 CCSprite 的方法,正如 documentation 所说:

    @interface Mos : CCSprite {
        // remove the line CCSprite *mos;
    }
    
    @implementation Mos
    
    // You probably don't need to override this method if you will not add other code inside of it
    -(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect
    {
       if( (self=[super initWithTexture:texture rect:rect]))
       {
    
       }
       return self;
    }
    
    + (id)sprite
    {
        return [Mos spriteWithFile:@"sprite_mos.png"];
    }
    
    @end
    

    那么在你的代码中,就可以正常使用Mos了:

    Mos *mos = [Mos sprite];
    [scene addChild:mos];
    

    【讨论】:

    • 谢谢你,但我希望有一种方法可以让精灵的 iamge 直接在 CCSprite 子类中,因为我希望以后可以为精灵设置动画。
    • 对了,[scene addChild:mos];出现一个错误,显示使用未声明的标识符“场景”。我打算在哪里宣布这一点?
    • @akuritsu - 我修改了代码,现在你不需要每次都指定文件了。
    • @akuritsu,您可以将scene 修改为您的场景的实际名称。我不知道是什么所以我以scene 为例。
    • 这么想,我只是用 [self adchild 替换它
    【解决方案2】:

    添加 CCSprite 和其他类的方式相同。

    Mos *newMos = [[Mos alloc] init];
    // set coordinates and other properties
    [scene addChild:newMos];
    [newMos release];
    

    编辑:

    @interface Mos : CCSprite {
        // some member variables go here
    }
    
    @implementation Mos
    
    -(id)init
    {
        CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:@"sprite_mos.png"];
        if( texture ) {
            CGRect rect = CGRectZero;
            rect.size = texture.contentSize;
            // set members to some values
            return [self initWithTexture:texture rect:rect];
        }
        [self release];
        return nil;
    }
    

    然后在你的场景类中

    // ...
    Mos *obj = [[Mos alloc] init];
    // set position, etc
    [scene addChild:obj];
    [obj release];
    // ...
    

    【讨论】:

    • 所以我猜我把它放到了我的游戏场景中?
    • 是的,但是您必须为 Mos 对象定义纹理(否则您应该将 [newMos mos] 作为子对象添加到场景中)。
    • 我不能在我的 CCSprite 课程中这样做吗?
    • 当然可以,但不能像第一篇文章中那样。
    • 好的,我将如何在我的课堂上做到这一点,因为这就是我想要实现的目标。也许您可以将代码发布为答案而不是评论?或者只是编辑当前答案
    猜你喜欢
    • 2011-07-30
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    相关资源
    最近更新 更多