swift - 如何将此类激活给另一个

标签 swift sprite-kit accelerometer core-motion

我对在我的主要 GameplayScene 中使用另一个类有疑问。我想要做的是让手机 X 轴的运动左右移动角色。这是我的 MotionClass.swift 中的内容

import SpriteKit
import CoreMotion

class MotionClass: SKScene {

    var player: Player?

    var motionManager = CMMotionManager()
    var destX: CGFloat = 0.0

    override func sceneDidLoad() {

            motionManager.accelerometerUpdateInterval = 0.2
            motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in
                if let myData = data {

                    let currentX = self.player?.position.x

                    if myData.acceleration.x > 0.2 {
                        self.destX = currentX! + CGFloat(myData.acceleration.x * 100)
                        print("Tilted Right")

                    } else {

                    if myData.acceleration.x < -0.2 {
                        self.destX = currentX! + CGFloat(myData.acceleration.x * 100)
                        print("Tilted Left")
                    }
                }
            }
        }
    }

    override func update(_ currentTime: TimeInterval) {

        let action = SKAction.moveTo(x: destX, duration: 1)
        self.player?.run(action)
    }

}

现在我正尝试在我的 GameplayScene.swift 中的 motionBegan 函数中调用此类,但我不知道该怎么做。我有变量 'grapple' 作为 MotionClass?但我不知道从那里去哪里。任何人都可以举一个很好的例子吗?

最佳答案

我认为您可能对 SKScene 子类的用途感到困惑,这就是您当前的 MotionClass。 (主要思想)是一次只使用一个 SKScene:如果你需要 MotionClass 的东西,那么你应该把它做成一个普通类,而不是 SKScene 子类。

我认为您可能还需要更加熟悉 OOP...在 static 属性/函数之外,您不会“调用”一个类,您 实例化它(你创建一个对象:])

因此,如果您想在 GamePlayClass 中访问 MotionClass 中的好东西,您需要对 MotionClass 对象的引用

这可以通过一个简单的全局变量来完成...我建议将其放入您的 GameViewController.swift 中:

// Here is a global reference to an 'empty' motion class object..
var global_motionClassObject = MotionClass()

class GameViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    // ...
    if let view = self.view as! SKView? else {
      let scene = MotionClass(size: view.frame.size)
      // Assign our global to the new scene just made:
      global_motionClassObject = scene
      scene.scaleMode = .aspectFit

      view.presentScene(scene)
    }

    // ...
}

现在在您的 GamePlayClass 内部,或其他任何地方,您可以通过调用 global_motionClassObject 访问 MotionClass

但是,这可能不会给出预期的结果,因为我担心您可能需要将您的 MotionClass 重组为 SKScene 以外的东西:)

关于swift - 如何将此类激活给另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43808237/

相关文章:

IOS Swift - 自定义相机覆盖

ios - 尝试制作一个平台,让我可以从下面跳过去,但可以降落在上面。难以微调逻辑

ios - iPhone 可以在没有 Watch App 的情况下从 Watch 检索加速度计数据吗?

accelerometer - 如何使用加速度计和陀螺仪数据确定相对位置

iphone - iPhone 加速度计究竟测量什么?

ios - swift : How can I resize the View Background Image?

ios - 如何在 Swift 中不向 NSJSONSerialization.JSONObjectWithData 传递任何选项

swift - macOS WKWebView 背景透明度

swift - Apple 的 Swift Sprite Kit : linearDamping, 这个属性在数学上是如何使用的?

swift - 如何通过 Sprite Kit Swift 中的分数来增加 SKAction.moveToY 中的数字?