gpt4 book ai didi

swift - SpriteKit : SKSpriteNode controlled by device motion falls out of the screen in the corners

转载 作者:行者123 更新时间:2023-11-28 09:17:13 25 4
gpt4 key购买 nike

我正在创建一个 SpriteKit 游戏,它使用 CoreMotion 框架在屏幕上移动 SKSpriteNode userNode。对于缩放,我将其设置为 ResizeFill,并使用 view.frame 将 View 的四个边界存储在变量中:

//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
}

}

然而,由于某种原因,当节点到达 View 的角落时,它会脱离 View 。我也尝试过 self.physicsBody = SKPhysicsBody(edgeLoopF​​romRect(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的代码,设置在update函数中运行:

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()
}
})
}
}

最佳答案

keepUserNodeOnScreen 中,您的 if/else 语句并未测试 userNode 退出屏幕的所有可能方式。删除所有 else 语句将解决此问题。

另一种方法是添加边循环

self.physicsBody = SKPhysicsBody(edgeLoopFromRect(view.frame))

并使用 applyForceapplyImpulse 移动 userNode 而不是通过更改其位置属性来移动它。如果节点的位置发生变化,SpriteKit 不会直接检测碰撞。

关于swift - SpriteKit : SKSpriteNode controlled by device motion falls out of the screen in the corners,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com