当玩家触摸时,下面的代码假设将节点移动到 MaxX
。一旦到达该点,就会将节点的移动重定向到 MinX
,反之亦然。
就目前情况而言,我只能将玩家向一个方向移动,并且它会忽略 movePlayer()
逻辑。
行动声明
var moveRightTest:Bool = true;
var moveLeftTest:Bool = false;
let moveRight = SKAction.moveByX(1000, y: 0, duration: 2);
let moveLeft = SKAction.moveByX(-1000, y: 0, duration: 2);
游戏场景内部:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
movePlayer();
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
stopPlayer();
}
func movePlayer() {
if(moveRightTest == true) {
if(player.position.x <= CGRectGetMaxX(self.frame)) {
player.runAction(moveRight);
} else {
moveRightTest = false;
moveLeftTest = true;
}
}
else if(moveLeftTest == true) {
if(player.position.x >= CGRectGetMinX(self.frame)) {
player.runAction(moveLeft);
} else {
moveLeftTest = false;
moveRightTest = true;
}
}
}
func stopPlayer() {
player.removeAllActions();
}
注意:我用整数/ float 替换了一些变量,以从代码中删除计算以便呈现。与该问题无关。我也刚刚学习 Swift。
最佳答案
现在,您的函数 movePlayer
在您调用它时仅执行一次,因此播放器会到达右边缘并停止。您需要在每次运行后重复以下步骤。为此,您可以将 runAction
与 completion
一起使用,如下所示:
isRight: Bool = true
let moveRight = SKAction.moveToX(CGRectGetMaxX(self.frame), duration: 2)
let moveLeft = SKAction.moveToX(CGRectGetMinX(self.frame), duration: 2)
func movePlayer() {
if isRight {
player.runAction(moveRight, completion: { () -> Void in
isRight = false
self.movePlayer()
})
} else {
player.runAction(moveLeft, completion: { () -> Void in
isRight = true
self.movePlayer()
})
}
}
关于ios - 触摸时重定向 SKNode SkAction 方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33811098/