ios - 当设备笔直且不倾斜时,如何让我的加速度计不移动我的节点?

标签 ios swift sprite-kit accelerometer

我有一个游戏,当我向左和向右倾斜时移动我的节点。但是,当我保持设备笔直时,我希望它停止节点并添加节点的图像,这样就不会有灰色和白色的棋盘。我该怎么做?正如您在我的代码中看到的,我使用 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/

相关文章:

html - iPhone SE 无法正确显示响应表标题,但可以在 Android 上运行

ios - AVAudioPlayer 没有从临时文件路径播放声音

ios - 在 Objective-C 的 Sprite-Kit 项目中,如何在 MyScene 之外的类中调用 update 方法?

ios - 随着数组大小的增加,应用程序崩溃

ios - NSAttributedString:非段落标题

ios - UIButton 左上角和左下角半径显示不正确

ios - UIView 不显示为 subview

swift - 使用 Swift 4 创建 SKSpriteNode 类

swift - SKSpriteNode放置后位置变化

iOS 应用程序错误 - 无法将自身添加为 subview