[英]Split Screen into Two View Controllers SpritKit + Swift
我正在使用SpriteKit + Swift制作一个简单的Pong游戏。 我正在尝试移动两个桨,即使手指已经在触摸显示屏了。 我有个建议将屏幕分成两个View Controller。 这会有所帮助吗? 如果是这样,将如何进行? 链接到上一个问题。
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
}
您提供的代码的主要问题在于您仅使用第一触键,当您有两个人来回移动拨片时,这不好。 我实际上不会使用touchesBegan
或touchesEnded
。 我将假设游戏场在水平方向上具有x
,因此512(默认场景宽度除以2)将成为中间线,并且桨位于x = 0
和x = 1024
。
下面的代码在touchesMoved
,并处理每一次移动的触摸。 如果触摸位置在屏幕的一侧,则它将获得该侧的拨片并进行移动。 您可能还希望将此代码放入touchesBegan
方法中,以便用户可以触摸他们希望操纵板移动的位置。 您可以回到桨检测方法(除了不使用每一次触摸,我都没有发现任何问题),但是我建议使用paddle.containsPoint
来测试触摸是否在内部。
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: UITouch in touches {
let location = touch.locationInNode(self)
if location.x < 512 {
let paddle = self.childNodeWithName(PaddleCategoryName) as! SKSpriteNode
paddle.position.y = location.y
} else {
let paddle2 = self.childNodeWithName(PaddleCategoryName2) as! SKSpriteNode
paddle2.position.y = location.y
}
}
}
我目前正在下载Xcode 7以获取Swift 2,并将使用适当的语法对其进行编辑。 但是现在,只需进行一些更改(例如方法调用),它就可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.