我有一个游戏,当我向左和向右倾斜时移动我的节点。但是,当我保持设备笔直时,我希望它停止节点并添加节点的图像,这样就不会有灰色和白色的棋盘。我该怎么做?正如您在我的代码中看到的,我使用 SKTexture 来更改节点图像和移动节点的速度。当设备笔直且不倾斜且节点不移动时,如何更改图像?谢谢!
func addTilt() {
if (motionManager.accelerometerAvailable) {
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) {
(data, error) in
if(data.acceleration.x < -0.05) { // tilting the device to the right
self.heroNode.accelerometerActive == true
self.heroNode.physicsBody?.velocity = CGVector(dx: -250, dy: 0)
self.heroNode.texture = SKTexture(imageNamed: "heroNode1")
} else if (data.acceleration.x > 0.05) { // tilting the device to the left
self.heroNode.accelerometerActive == true
self.heroNode.physicsBody?.velocity = CGVector(dx: 250, dy: 0)
self.heroNode.texture = SKTexture(imageNamed: "heroNode2")
}
}
}
最佳答案
看起来您可以在当前逻辑中添加一个 else
来处理 X 加速度大于 -0.05 且小于 0.05 时的情况,这主要是直立的,在任一方向上只有一点点倾斜.
此外,您应该使用 =
进行赋值,而不是 ==
,它测试相等性并且对您的 accelerometerActive
的值没有影响属性。
而且,如果是我,我会通过放弃额外的括号来保持代码更简洁,因为在 Swift 中你不需要它们。
if motionManager.accelerometerAvailable { // No parenthesis
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) { (data, error) in
if data.acceleration.x < -0.05 { // tilting the device to the right
self.heroNode.accelerometerActive = true
self.heroNode.physicsBody?.velocity = CGVector(dx: -250, dy: 0)
self.heroNode.texture = SKTexture(imageNamed: "heroNode1")
} else if data.acceleration.x > 0.05 { // tilting the device to the left
self.heroNode.accelerometerActive = true
self.heroNode.physicsBody?.velocity = CGVector(dx: 250, dy: 0)
self.heroNode.texture = SKTexture(imageNamed: "heroNode2")
} else { // straight
self.heroNode.accelerometerActive = false
self.heroNode.physicsBody?.velocity = CGVector(dx: 0, dy: 0) // No velocity
self.heroNode.texture = SKTexture(imageNamed: "heroNode3") // Image when straight
}
}
}
关于ios - 当设备笔直且不倾斜时,如何让我的加速度计不移动我的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31322535/