hello world
hello world

Reputation: 61

Calling a method from another class - SpriteKit/Objective C

I'm programming a little SpriteKit game and I need some help regarding my enemy classes. I separated the enemy's "AI" from the gamescene itself and I'm calling it's methods from inside the game scene, just like that:

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];
}

However, the enemy wont spawn. It's not adding the enemy child I think. I also tested out if the method is called by using NSLog and it actually showed up in the console, so what am I doing wrong?

Edit: 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

Upvotes: 0

Views: 454

Answers (1)

0x141E
0x141E

Reputation: 12753

The issue is you are not adding the enemies to the scene. You are adding it to an instance of Enemyclass. The following should correct this issue:

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

Your Enemyclass.m should look like this:

-(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];
}

NEW EDITS: Change GameScene to SKScene in Enemyclass.h

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

and Enemyclass.m

-(void)enemiesLevel1:(SKScene *)scene

You no longer need this in Enemyclass.h, so delete it

#import "GameScene.h"

Upvotes: 3

Related Questions