根据精灵的当前位置让精灵去某个位置?

时间:2014-08-16 05:15:21

标签: ios if-statement ios7 sprite-kit sprite

我认为我的头衔相当令人困惑,但我并不确定如何标题。这是我目前的代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
SKAction *moveNodeRight = [SKAction moveByX:-209.0 y:0.0 duration:0.85];
 [_squirrelSprite runAction: moveNodeRight withKey:@"changeside"];
//_squirrelSprite.xScale = -1.0;

if(_squirrelSprite.xScale == -1.0)
{
    _squirrelSprite.xScale = 1.0;
} else {
    _squirrelSprite.xScale = -1.0;
}
}

当我点击屏幕时,精灵移动到一个新位置(X:-209.0,Y:0.0)。新位置位于当前位置的左侧。当我第二次点击屏幕时,精灵只是向左移动离开屏幕。

我想要的是:我对目前的情况感到满意,但是当精灵处于新位置时(X:-209.0,Y:0.0),我希望第二次点击将其返回给它& #39;原来的位置。我认为它看起来像上面的代码,但到目前为止没有任何工作。下面是它可能看起来像什么的想法。谢谢!

if(_squirrelSprite.position == the second position)
{
    _squirrelSprite.position = the first position;
} else {
    _squirrelSprite.xScale = the second position;
}

1 个答案:

答案 0 :(得分:1)

当用户点击屏幕时,这会将节点从一个位置移动到另一个位置。然后,当用户再次点击屏幕时,它会将节点移回原始位置。

@interface MyScene()

@property SKSpriteNode *squirrelSprite;
@property BOOL atFirstPosition;
@property CGPoint firstPosition;

@end

@implementation MyScene

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        _firstPosition = CGPointMake(300, self.frame.size.height/2);
        _squirrelSprite = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(32, 32)];
        _squirrelSprite.position = _firstPosition;
        _atFirstPosition = YES;
        [self addChild:_squirrelSprite];
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (_atFirstPosition)
    {
        SKAction *moveNodeLeft = [SKAction moveByX:-209.0 y:0.0 duration:0.85];
        [_squirrelSprite runAction: moveNodeLeft withKey:@"changeside"];
    } else {
        _squirrelSprite.position = _firstPosition;
    }
    _atFirstPosition = !_atFirstPosition;
    _squirrelSprite.xScale *= -1.0;
}

@end

修改 这会使用SKAction将节点移回其原始位置

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (_atFirstPosition)
    {
        SKAction *moveNodeLeft = [SKAction moveByX:-209.0 y:0.0 duration:0.85];
        [_squirrelSprite runAction: moveNodeLeft withKey:@"moveleft"];
    } else {
        SKAction *moveNodeRight = [SKAction moveByX:209.0 y:0.0 duration:0.85];
        [_squirrelSprite runAction: moveNodeRight withKey:@"moveright"];
    }
    _atFirstPosition = !_atFirstPosition;
    _squirrelSprite.xScale *= -1.0;
}