gpt4 book ai didi

ios - 如何在实例方法中访问类方法变量或对两者使用公共(public)变量?

转载 作者:行者123 更新时间:2023-11-28 21:41:53 24 4
gpt4 key购买 nike

我有这个类方法来创建英雄对象。

+(id)hero
{
NSArray *heroWalkingFrames;
//Setup the array to hold the walking frames
NSMutableArray *walkFrames = [NSMutableArray array];
//Load the TextureAtlas for the hero
SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
//Load the animation frames from the TextureAtlas
int numImages = (int)heroAnimatedAtlas.textureNames.count;
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
[walkFrames addObject:temp];
}
heroWalkingFrames = walkFrames;
//Create hero sprite, setup position in middle of the screen, and add to Scene
SKTexture *temp = heroWalkingFrames[0];

Hero *hero = [Hero spriteNodeWithTexture:temp];
hero.name =@"Hero";
hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
hero.physicsBody.categoryBitMask = heroCategory;
hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
return hero;
}

我还有另一个实例方法来为我的英雄执行奔跑动画。

-(void)Start
{
SKAction *incrementRight = [SKAction moveByX:10 y:0 duration:.05];
SKAction *moveRight = [SKAction repeatActionForever:incrementRight];
[self runAction:moveRight];
}

现在 Start 方法中的 heroWalkingFrames 变量让我可以执行动画,我想在 Start 方法中添加这一行

 [SKAction repeatActionForever:[SKAction animateWithTextures:heroWalkingFrames timePerFrame:0.1f resize:NO restore:YES]];

有什么办法可以同时使用这个变量吗?

最佳答案

当然,在Hero.h中添加:

@property (nonatomic, retain) NSArray *walkingFrames;

然后,在您的 +(id)hero 方法中,不要声明一个新数组 NSArray *heroWalkingFrames,而是使用:

+(id)hero
{
//Setup the array to hold the walking frames
NSMutableArray *walkFrames = [NSMutableArray array];
//Load the TextureAtlas for the hero
SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
//Load the animation frames from the TextureAtlas
int numImages = (int)heroAnimatedAtlas.textureNames.count;
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
[walkFrames addObject:temp];
}

//We set hero texture to the first animation texture:
Hero *hero = [Hero spriteNodeWithTexture:walkFrames[0]];
// Set the hero property "walkingFrames"
hero.walkingFrames = walkFrames;

hero.name =@"Hero";
hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
hero.physicsBody.categoryBitMask = heroCategory;
hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
return hero;
}

关于ios - 如何在实例方法中访问类方法变量或对两者使用公共(public)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31740027/

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