我正在使用SpriteKit + Swift制作简单的Pong游戏。即使手指已经触摸显示屏,我也试图移动两个拨片。我有一个建议将屏幕分成两个View Controller。这会有帮助吗?如果是这样,怎么办呢? Link to previous question.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first as UITouch?
let touchLocation = touch?.locationInNode(self)
let body: SKPhysicsBody? = self.physicsWorld.bodyAtPoint(touchLocation!)
if body?.node!.name == PaddleCategoryName {
print("Paddle Touched!")
fingerIsOnPaddle = true
}
if body?.node!.name == PaddleCategoryName2 {
print("Paddle2 Touched!")
fingerIsOnPaddle2 = true
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if fingerIsOnPaddle {
let touch = touches.first as UITouch?
let touchLocation = touch?.locationInNode(self)
let previousTouchLocation = touch?.previousLocationInNode(self)
let paddle = self.childNodeWithName(PaddleCategoryName) as! SKSpriteNode
var newYPosition = paddle.position.y + (touchLocation!.y - previousTouchLocation!.y)
newYPosition = max(paddle.size.height / 2, newYPosition)
newYPosition = min(self.size.height - paddle.size.height / 2, newYPosition)
paddle.position = CGPointMake(paddle.position.x, newYPosition)
}
if fingerIsOnPaddle2 {
let touch = touches.first as UITouch?
let touchLocation = touch?.locationInNode(self)
let previousTouchLocation = touch?.previousLocationInNode(self)
let paddle2 = self.childNodeWithName(PaddleCategoryName2) as! SKSpriteNode
var newYPosition = paddle2.position.y + (touchLocation!.y - previousTouchLocation!.y)
newYPosition = max(paddle2.size.height / 2, newYPosition)
newYPosition = min(self.size.height - paddle2.size.height / 2, newYPosition)
paddle2.position = CGPointMake(paddle2.position.x, newYPosition)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
fingerIsOnPaddle = false
fingerIsOnPaddle2 = false
}
答案 0 :(得分:0)
您提供的代码的主要问题是您只使用第一次触摸 ,当您有两个人移动拨片时这不好。我实际上不会使用touchesBegan
或touchesEnded
。我将假设游戏区域沿水平方向将x
,因此512(默认场景宽度除以2)将是中间线,其中拨片位于x = 0
和{ {1}}。
以下代码位于x = 1024
,处理移动的每一次触摸。如果触摸位置位于屏幕的一侧,则它将获得该侧的桨并移动它。您可能希望将此代码放在touchesMoved
方法中,以便用户可以触摸他们想要拨片的位置。您可以回到您的桨式检测方法(除了不使用每次触摸之外我没有看到任何问题),但我建议使用touchesBegan
测试触摸是否在内部。
paddle.containsPoint
我目前正在下载Xcode 7以获得Swift 2,我将使用正确的语法对其进行编辑。但是现在,通过一些更改(比如方法调用),它应该可以工作。