从另一个类调用方法 - SpriteKit / Objective C.

时间:2014-08-20 20:50:37

标签: objective-c sprite-kit

我正在编写一个小的SpriteKit游戏,我需要一些关于我的敌人类的帮助。 我将敌人的“AI”与游戏本身分开,我从游戏场景中调用它的方法,就像那样:

GameScene.m:

-(void)enemiesLevel1{
    EnemyClass* wave1 = [[EnemyClass alloc] init];
    [wave1 enemiesLevel1];
}

Enemyclass.m:

-(void)enemiesLevel1
{
    EnemyName = @"enemy1";
    SKSpriteNode* enemy = [SKSpriteNode spriteNodeWithImageNamed:EnemyName];
    pathSpeed = 5;
    CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(0,0,10,10), NULL);
    SKAction *followTrack = [SKAction followPath:path
                                        asOffset:NO
                                    orientToPath:YES
                                        duration:pathSpeed];
    SKAction *forever = [SKAction repeatActionForever:followTrack];

    [self addChild:enemy];
    [enemy runAction:forever];
}

然而,敌人不会产卵。我认为这不会增加敌人的孩子。我还测试了是否使用NSLog调用该方法并且它实际上出现在控制台中,所以我做错了什么?

编辑:EnemyClass.h

#import <Foundation/Foundation.h>
#import <SpriteKit/SpriteKit.h>
#import "GameScene.h"

@interface EnemyClass: SKNode
-(void)enemiesLevel1:(GameScene *)scene; //Expected a type (Pointing to "GameScene *")
@end

1 个答案:

答案 0 :(得分:3)

问题是你没有将敌人添加到场景中。您正在将其添加到Enemyclass的实例中。以下内容应解决此问题:

-(void)enemiesLevel1{
    EnemyClass* wave1 = [[EnemyClass alloc] init];
    // Pass the scene to your enemy class method
    [wave1 enemiesLevel1:self];
}

你的Enemyclass.m应该是这样的:

-(void)enemiesLevel1:(SKScene *)scene
{
    EnemyName = @"enemy1";
    SKSpriteNode* enemy = [SKSpriteNode spriteNodeWithImageNamed:EnemyName];
    pathSpeed = 5;
    CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(0,0,10,10), NULL);
    SKAction *followTrack = [SKAction followPath:path
                                        asOffset:NO
                                    orientToPath:YES
                                        duration:pathSpeed];
    SKAction *forever = [SKAction repeatActionForever:followTrack];

    // Add enemy to scene not self
    [scene addChild:enemy];
    [enemy runAction:forever];
}

新编辑:在Enemyclass.h中将GameScene更改为SKScene

-(void)enemiesLevel1:(SKScene *)scene;

和Enemyclass.m

-(void)enemiesLevel1:(SKScene *)scene

你不再需要在Enemyclass.h中,所以删除它

#import "GameScene.h"