سؤال

I'm building a game where the user selects a type of weapon at the start. I have an SKSword class but I want to be able to set the type it is. I want to implement it like the following:

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

So that I can call:

[weapon specialAttack];

and it will do an action specific to the sword specified (e.g HeavySword)

هل كانت مفيدة؟

المحلول

Option 1

What you're trying to do is built into Objective-C. Define a method called specialAttack in your Sword class:

@interface Sword : SKNode

    -(void) specialAttack;

@end

Then write a blank implementation:

@implementation Sword

    -(void) specialAttack
    {
        return;
    }

@end

Now, create a subclass called HeavySword using Sword as the base class:

@interface HeavySword : Sword

    -(void) specialAttack;

@end

...

@implementation HeavySword

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

Now, just create an object of type HeavySword:

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

...

[weapon specialAttack];

I'd also suggest using your own prefix other than SK, which implies a class is part of Sprite Kit.

Option 2

Use typedef enum to define some constants:

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

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

You can then declare some properties and an init method in your interface:

@interface Sword : SKNode

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

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

    -(void) specialAttack;

@end

Finally, in your implementation:

@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.
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top