1

我正在构建一个游戏,用户在开始时选择一种武器。我有一个 SKSword 类,但我希望能够设置它的类型。我想像下面这样实现它:

JBSword *weapon = [[JBSword alloc]initWithSwordType:HeavySword HandelType:Grip];

这样我就可以打电话了:

[weapon specialAttack];

它将执行特定于指定剑的动作(例如HeavySword)

4

1 回答 1

4

选项1

您正在尝试做的是内置到 Objective-C 中。specialAttack定义一个在你的Sword类中调用的方法:

@interface Sword : SKNode

    -(void) specialAttack;

@end

然后写一个空白实现:

@implementation Sword

    -(void) specialAttack
    {
        return;
    }

@end

现在,创建一个名为HeavySwordusingSword作为基类的子类:

@interface HeavySword : Sword

    -(void) specialAttack;

@end

...

@implementation HeavySword

-(void) specialAttack
{
    // HeavySword code here
}

现在,只需创建一个类型的对象HeavySword

Sword *weapon = [[HeavySword alloc] init];

...

[weapon specialAttack];

我还建议使用您自己的前缀而不是 SK,这意味着一个类是 Sprite Kit 的一部分。

选项 2

用于typedef enum定义一些常量:

typedef enum {
    kHeavySwordType,
    kLightSwordType,
    kDualSwordType,
    ...
} SwordType;

typedef enum {
    kWoodHandleType,
    kGoldHandleType,
    kDiamondHandleType,
    ...
} HandleType;

然后,您可以在界面中声明一些属性和一个 init 方法:

@interface Sword : SKNode

    @property (nonatomic) SwordType type;
    @property (nonatomic) HandleType handle;

    -(id) initWithType:(SwordType) type handle:(HandleType) handle;

    -(void) specialAttack;

@end

最后,在您的实现中:

@implementation Sword

-(id) initWithType:(SwordType) type handle:(HandleType) handle
{
    if(self = [super init]) {
        _type = type;     // Use _type within int, and self.type everywhere else
        _handle = handle; // Same thing here.
    }
    return self;
}

-(void) specialAttack
{
    // Code goes here
    // Use self.type and self.handle to access the sword and handle types.
}
于 2013-11-03T22:39:20.470 回答