如何在spritekit中存储位置

时间:2014-03-25 00:16:09

标签: ios xcode game-engine sprite-kit

我需要在游戏中改变角色外观。我的角色由一个节点定义:

SKSpriteNode* _character;
....
 SKTexture* tmp = [SKTexture textureWithImageNamed:string];
            tmp.filteringMode = SKTextureFilteringNearest;

            [textureArray addObject:tmp];
            _character = [SKSpriteNode spriteNodeWithTexture:tmp];

然后在游戏中的某个条件下,如果我检查它是否满意,我会改变外观:

-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
if (condition_satisfied) {
...
_store.position = _character.position;

[_character removeFromParent];
...
//load new character texture here, I won't post the code, for short. Then
....
_character.position = _store.position;
...
[self addChild:_character];
}

我使用商店节点来存储位置,因为我的角色的位置会在游戏中通过人为触摸而改变。但是在游戏中,它总会导致崩溃,碰撞......所以我猜这不是恢复角色正确位置的正确方法。 我该怎么办?

2 个答案:

答案 0 :(得分:0)

要更改纹理,只需设置SKSpriteNode' s texture属性:

_character.texture = [SKTexture textureWithImageNamed:@"image"];

或者使用SKAction,如果你想在纹理改变时添加一些褪色效果:

SKAction *fadeOut = [SKAction fadeOutByDuration:0.3f];
SKAction *fadeIn = [SKAction fadeInByDuration:0.3f];
SKAction *changeTexture = [SKTexture setTexture:[SKTexture textureWithImageNamed:@"image"]];
[_character runAction:[SKAction sequence:@[fadeOut,changeTexture,fadeIn]]];

无需removeFromParent节点。

如果您需要存储节点的位置,最好将其存储在@property中:

@interface GameScene()

@property (nonatomic) CGPoint characterPosition;

@end

@implementation GameScene

-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
if (condition_satisfied) {
...
self.characterPosition = _character.position;

[_character removeFromParent];
...
//load new character texture here, I won't post the code, for short. Then
....
_character.position = self.characterPosition;
...
[self addChild:_character];
}

@end

答案 1 :(得分:0)

您可以在CGPoint变量中执行此操作,而不是创建SKSpriteNode来存储节点的位置。

-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
if (condition_satisfied) {
...
CGPoint characterPosition = _character.position;

[_character removeFromParent];
...
//load new character texture here, I won't post the code, for short. Then
....
_character.position = characterPosition;
...
[self addChild:_character];
}