我正在创建一个SpriteKit游戏,该游戏使用CoreMotion框架在屏幕周围移动SKSpriteNode userNode
。对于缩放,我将其设置为ResizeFill,并使用view.frame将视图的四个边界存储在变量中:
//setting screens bounds
var rightBound = CGFloat()
var leftBound = CGFloat()
var upperBound = CGFloat()
var bottomBound = CGFloat()
rightBound = view.frame.width - (userNode.size.width / 2)
leftBound = CGRectGetMinX(view.frame) + (userNode.size.width / 2)
upperBound = view.frame.height - (userNode.size.height / 2)
bottomBound = CGRectGetMinY(self.frame) + (userNode.size.height / 2)
为了尝试在屏幕上保留userNode
,我创建了一个在更新功能中运行的函数:
func keepUserNodeOnScreen(){
if userNode.position.x >= rightBound{
userNode.position.x = rightBound
}
else if userNode.position.x <= leftBound{
userNode.position.x = leftBound
}
else if userNode.position.y >= upperBound{
userNode.position.y = upperBound
}
else if userNode.position.y <= bottomBound{
userNode.position.y = bottomBound
}
}
但是,出于某种原因,当节点到达视图的角落时,它会脱离视图。我也试过self.physicsBody = SKPhysicsBody(edgeLoopFromRect(view.frame))
,但这也没有用。有什么可能导致这种情况?
编辑: 这是userNode生成代码:
userNode.color = SKColor.redColor()
userNode.size = CGSizeMake(15, 15)
userNode.position = CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)
userNode.physicsBody = SKPhysicsBody(rectangleOfSize: userNode.size)
userNode.physicsBody?.dynamic = true
userNode.physicsBody?.allowsRotation = false
userNode.physicsBody?.categoryBitMask = userCategory
userNode.physicsBody?.contactTestBitMask = bulletCategory
self.addChild(userNode)
以下是移动userNode
的代码,设置为在更新函数中运行:
func moveUserNode(){
if motionManager.accelerometerAvailable == true{
motionManager.deviceMotionUpdateInterval = 0.001
motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{
deviceManager, error in
if self.gameOn == true{
var roll: CGFloat = CGFloat(self.motionManager.deviceMotion.attitude.roll)
var pitch: CGFloat = CGFloat(-self.motionManager.deviceMotion.attitude.pitch) + CGFloat(0.6)
//Keep userNode on screen
self.newPosition.x = self.userNode.position.x + CGFloat(roll) * 20
self.newPosition.y = self.userNode.position.y + CGFloat(pitch) * 20
self.userNode.position = self.newPosition
}
else if self.gameOn == false{
self.motionManager.stopDeviceMotionUpdates()
}
})
}
}
答案 0 :(得分:0)
在keepUserNodeOnScreen
中,您的if/else
语句未对userNode
退出屏幕的所有可能方式进行测试。删除所有else
语句将解决此问题。
另一种方法是添加边循环
self.physicsBody = SKPhysicsBody(edgeLoopFromRect(view.frame))
并使用userNode
或applyForce
移动applyImpulse
,而不是通过更改其位置属性来移动它。如果节点的位置直接改变,SpriteKit不会检测到碰撞。