iOS SpriteKit创建和显示来自另一个类的对象

时间:2014-04-27 13:48:56

标签: ios class sprite-kit addchild

我是SpriteKit的新手,我试图在MyScene.m中显示在课堂上创建的对象(圆圈)。这就是我所拥有的:

在CreateNewCircle.h中我写道:

#import <SpriteKit/SpriteKit.h>

@interface CreateNewCircle : SKScene

-(void) addNewCircle;

@end

并在.m(CreateNewCircle.m)中:

#import "CreateNewCircle.h"

@implementation CreateNewCircle

-(void) addNewCircle {

    const CGSize size = self.frame.size;

    const CGPoint center = CGPointMake(size.width * 0.5, size.height * 0.5);

    CGRect box = CGRectMake(center.x - 40.0, center.y - 40.0, 80.0, 80.0);

    SKShapeNode *shapeNode = [[SKShapeNode alloc] init];
    shapeNode.path = [UIBezierPath bezierPathWithOvalInRect:box].CGPath;
    shapeNode.fillColor = [SKColor redColor];
    shapeNode.strokeColor = nil;
}

@end

现在我试图通过MyScene.m调用此方法(在屏幕上显示一个圆圈):

MyScene.h:

#import <SpriteKit/SpriteKit.h>

@interface MyScene : SKScene

@end

MyScene.m:

#import "MyScene.h"
#import "CreateNewCircle.h"

@implementation MyScene {

}

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */
        self.backgroundColor = [SKColor colorWithWhite:255 alpha:1.0];

        CreateNewCircle *circle1 = [[CreateNewCircle alloc] init];
        [circle1 addNewCircle];

        [self.scene addChild:circle1];

    }
    return self;
}

构建没问题,但是当我跑步时,什么都没有出现。我试图改变&#34; addchild&#34;行如:

[circle1 setName:@"circleOne"];

[self childNodeWithName:@"circleOne"];

但结果相同:空白屏幕。如果我直接在MyScene.m中编写相同的代码,则会出现圆圈,因此代码应该是正确的。可以请有人帮助我:-)?

感谢。

1 个答案:

答案 0 :(得分:0)

请查看此示例,以便您可以对代码进行更改:

<强> MyScene.h

#import <SpriteKit/SpriteKit.h>

@interface MyScene : SKScene

@end

<强> MyScene.m

#import "MyScene.h"
#import "CreateNewSprite.h"

@implementation MyScene
{
    //
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        CreateNewSprite *mySprite = [[CreateNewSprite alloc] init];
        [self addChild:mySprite];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)update:(CFTimeInterval)currentTime
{
    //
}

@end

<强> CreateNewSprite.h

#import <SpriteKit/SpriteKit.h>

@interface CreateNewSprite : SKShapeNode

@end

<强> CreateNewSprite.m

#import "CreateNewSprite.h"

@implementation CreateNewSprite

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        SKShapeNode *shape = [SKShapeNode node];
        shape.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(20, 20, 20, 20) cornerRadius:4].CGPath;
        shape.position = CGPointMake(100,100);
        shape.strokeColor = [SKColor redColor];

        [self addChild:shape];
    }
    return self;
}

@end