ios - 如何在手指触摸时移动 Sprite ?

标签 ios touch sprite-kit

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

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

我希望 Sprite 移动直到触摸结束。目前我只是沿着 x 轴移动它。

最佳答案

有多种方法可以做到这一点。

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

@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;
    }
}

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

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

关于ios - 如何在手指触摸时移动 Sprite ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22569549/

相关文章:

objective-c - 在 xcode 中使用 Sprite 表

ios - SpriteKit : Getting Audio to stop playing

iphone - 哪个适用于 iOS 的图像缓存库?

ios - 如何使用 UITextField Delegate 修改行为?

ios - 每次调用函数 Swift 3 时移动到数组中的下一个元素

c# - 确定 Windows 10 触摸键盘是可见还是隐藏

ios - 有没有软件方法可以将 "Wake"设置为 "Sleeping"iPhone 上的触摸屏?

javascript - 基于 HTML5/JavaScript 的游戏 - 通过触摸控制 x/y 坐标

ios - 呈现 UIImagePickerController 使应用程序崩溃

ios - SpriteKit类别BitMask问题