繁体   English   中英

手指触摸时如何移动精灵?

[英]How do i move the sprite while the finger is touching?

我正在开发一个小型游戏,以了解更多xcode和Objective-C。

我要在触摸时沿一个轴移动精灵。 我知道如何将SKAction与moveBy一起使用,但是精灵到达指定的距离时会停止移动。

我希望精灵移动直到触摸结束。 目前,我只沿x轴移动它。

您可以通过几种方法来执行此操作。

这是一个简单的touchesBegan:withEvent: :在touchesBegan:withEvent: ,将场景中的标志设置为YES以指示手指向下。 touchesEnded:withEvent: ,将标志设置为NO 在场景的update:方法中,如果标志为YES ,则修改精灵的位置。

@implementation MyScene {
    BOOL shouldMoveSprite;
    SKNode *movableSprite;
    NSTimeInterval lastMoveTime;
}

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    lastMoveTime = HUGE_VAL;
    shouldMoveSprite = YES;
}

 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    shouldMoveSprite = NO;
}

 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    shouldMoveSprite = NO;
}

static CGFloat kSpriteVelocity = 100;

- (void)update:(NSTimeInterval)currentTime {
    NSTImeInterval elapsed = currentTime - lastMoveTime;
    lastMoveTime = currentTime;
    if (elapsed > 0) {
        CGFloat offset = kSpriteVelocity * elapsed;
        CGPoint position = movableSprite.position;
        position.x += offset;
        movableSprite.position = position;
    }
}

另一种方法是,当触摸开始时,将自定义动作(使用+[SKAction customActionWithDuration:block:] )附加到稍微移动它的精灵上,并在触摸结束时删除该动作。

另一种方法是使用物理引擎。 当触摸开始时,将精灵的physicsBody.velocity设置为非零向量(或施加脉冲)。 触摸结束后,将速度设置回CGVectorMake(0,0)

这就是我所做的-不确定这是否是最有效的方法,但是它可以按照我想要的方式工作!

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.isFingerOnBowl)
    {
        UITouch *touch = [touches anyObject];
        CGPoint touchLocation = [touch locationInNode:self];
        moveBowlToPoint = [SKAction moveToX:(touchLocation.x) duration:0.01];
        [_bowl runAction:moveBowlToPoint];
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM