【问题标题】:Cocos2D - userData property for spriteCocos2D - sprite 的 userData 属性
【发布时间】:2011-09-02 20:11:31
【问题描述】:

我正在使用 Cocos2d 开发一个 iphone 游戏应用程序。

我发现这是解决我将整数存储到精灵属性的问题的一个很好的解决方案:

sprite.userData = 123;

但是 sprite.userData 只能存储一条数据。如果我需要存储三条数据,最好的方法是什么?

【问题讨论】:

    标签: cocos2d-iphone


    【解决方案1】:

    'userData' 实际上是 void 指针,没有被 'Node' 类保留:

    void *userData_;
    

    因此它可以指向任何数据结构或类(甚至是 C 函数)。

    【讨论】:

      【解决方案2】:

      对于一个或九个自定义变量,您最好的选择是继承 CCSprite 并将您的自定义变量作为新类的类变量,使用属性公开读/写它们。

      就像精通 Objective-C 的程序员会做的那样。

      要明确回答您的问题:您可以将 NSDictionary 或 NSArray 设置为 userData,它们本身可以包含多个项目。但是,如果您要走那么远:请阅读上文。

      【讨论】:

        【解决方案3】:

        将 ccsprite 类扩展为 userdata 类,并将该类用于您要创建的任何变量...但是您需要将该类用于所有检查和条件 ....

        这里拿代码

        用户数据.h

        //
        //  UserData.h
        //
        //
        
        
        #import "CCSprite.h"
        #import "Constants.h"
        
        @class GameLayer;
        @interface UserData : CCSprite {
            int userDataType;
            int tag;
            int parentTag;
              GameLayer *gameLayer;
            BOOL readyForDeletion; 
        }
        
        @property(nonatomic) int userDataType;
        @property(nonatomic) int tag;
        @property(nonatomic) int parentTag;
        @property(nonatomic, assign) GameLayer *gameLayer;
        @property(nonatomic) BOOL readyForDeletion;
        
        -(id) initWithSpriteName:(NSString *)spriteName;
        
        @end
        

        和 userdata.mm

            //
           //  UserData.mm
           //
           //
        
           #import "UserData.h"
        
           @implementation UserData
        
           @synthesize userDataType;
           @synthesize tag;
           @synthesize parentTag;
           @synthesize gameLayer;
           @synthesize readyForDeletion;
        
           -(id) initWithSpriteName:(NSString *)spriteName {
               if (self = [super initWithFileName:spriteName]) {
        
               }
               return self;
           }
        
           -(void) onExit {
               [super onExit];
           }
        
           -(void) dealloc {
               [super dealloc];
           }
        

        @结束

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-17
          • 1970-01-01
          相关资源
          最近更新 更多