gpt4 book ai didi

ios - 初始化子类不起作用

转载 作者:行者123 更新时间:2023-11-29 12:13:52 25 4
gpt4 key购买 nike

我想通过子类生成 spritenode 以进行屏幕显示,但它没有显示在屏幕上。有人知道我做错了什么吗?

子类

@implementation Seagull

-(id)init
{
self = [super init];
if (self) {
_atlas = [SKTextureAtlas atlasNamed:@"Seagull"];
_seagull = [SKSpriteNode spriteNodeWithTexture:[_atlas textureNamed:@"Seagull1"]];
_seagull.size = CGSizeMake(156.8, 115.4);

NSArray *flyFrames = @[[_atlas textureNamed:@"Seagull1"],
[_atlas textureNamed:@"Seagull2"]];

_flyAnimation = [SKAction repeatActionForever:[SKAction animateWithTextures:flyFrames timePerFrame:0.15 resize:NO restore:NO]];

[_seagull runAction:_flyAnimation];
}
return self;
}

@end

已创建子类对象

-(Seagull *)spawnSeagull
{
Seagull *seaGull = [[Seagull alloc] init];
seaGull.position = CGPointMake(self.size.width * 0.5, self.size.height * 0.5);
NSLog(@"seagull postion.x = %f && position.y = %f", seaGull.position.x, seaGull.position.y);
[self addChild:seaGull];

return seaGull;
}

添加到viewDidLoad中的场景

[self spawnSeagull];

最佳答案

您在 SKSpriteNode (Seagull) 中创建property SKSpriteNode (_seagull) 时出错.

在您的init 方法中,您将_seagull 初始化为一个SKSpriteNode,但是当生成海鸥时,您所做的只是创建和添加Seagull 类的实例到场景,与 _seagull 无关,它实际上包含海鸥的纹理。要解决此问题,您需要在 spawnSeagull 中返回 seaGull.seagull,这恐怕不是最佳做法。

但是,您的代码中仍有几个地方需要修复。

spawnSeagull 中:

  • CGPointMake(self.size.width * 0.5, self.size.height * 0.5) 是错误的,因为您不会以这种方式获得场景的一半大小。
  • 您应该在您的GameScene 中调用[self addChild:seaGull],因为您要将它添加到场景中,而不是添加到SKSpriteNode 的子类中

viewDidLoad中(推荐使用didMoveToView):

  • 正如@timgcarlson 评论的那样,您需要一个对象来为其分配spawnSeagull 的返回结果。

我在下面添加完整的代码:

去掉init,在子类中添加一个类方法,

+ (Seagull *)spawnSeagull
{
SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:@"Seagull"];
Seagull *seagull = [Seagull spriteNodeWithTexture:[atlas textureNamed:@"Seagull1"]];

// seagull.size = CGSizeMake(156.8, 115.4);
// May be set scale of seagull is better? like:
seagull.scale = 2.0;

NSArray *flyFrames = @[[atlas textureNamed:@"Seagull1"],
[atlas textureNamed:@"Seagull2"]];
SKAction *flyAnimation = [SKAction repeatActionForever:[SKAction animateWithTextures:flyFrames timePerFrame:0.15 resize:NO restore:NO]];

[seagull runAction:flyAnimation];

return seagull;
}

调用GameScene中的类方法,

- (void)didMoveToView:(SKView *)view
{
Seagull *seagull = [Seagull spawnSeagull];
seagull.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:seagull];
}

this Apple doc 中查找更多示例代码,它如何创建 shipSprite 会有所帮助。

关于ios - 初始化子类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32483402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com