我正在开发一个小游戏,以了解更多 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/