这可能是一个愚蠢的问题,但这是我的情况。

我有一个SKShapeNode rect,它在屏幕上从左到右依次如下:

      // GameScene.swift

  var rect = SKShapeNode()
  var counter = 0{

    didSet{
        rect.position = CGPoint(x: CGFloat(counter) , y: frame.midY)

        if CGFloat(counter) > frame.width{
            counter = 0
      }}}


override func update(_ currentTime: TimeInterval) {
    counter =       counter + 4
}

在ViewController.swift中,我尝试获取像这样的rect.position,我知道这是错误的,因为它创建了一个新实例。
//ViewController.swift

 let gameScene = GameScene()

@IBAction func button(_ sender: Any) {

//        gameScene.rect.position = games.frame.CGPoint(x: 200, y: 400)
          print(gameScene.rect.position)         // Always returns (0,0)

}

问题:如何从其他 class 实时获取rect.position。这样,每当我按下按钮时,我就会知道rect的实际位置?

更新

在罗恩的建议下,我从的viewDidLoad 中更新了ViewController.swift方法:
 let gameScene = GameScene()

   override func viewDidLoad() {
    super.viewDidLoad()


    if let view = self.spriteView {
        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {

            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
              }}

此:
   var gameScene : GameScene!

   override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.spriteView {
        // Load the SKScene from 'GameScene.sks'
        if let scene = GameScene(fileNamed: "GameScene") {    // SKScene changed to GameScene

            self.gameScene = scene                           // scene assigned to gameScene variable

            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }
    }

INTENTION
我想获得当单击play按钮时移动条的位置。
请注意,GameScene仅代表实际屏幕的一部分

ios - 获取Sprite在其他类(class)中的位置-LMLPHP

最佳答案

首次过渡到GameScene时(假设您直接从GameViewController转到GameScene),请为gameScene创建一个类级别的变量。然后,当您需要来自GameScene的信息时,请使用相同的变量,而不是创建一个新的GameScene变量

var gameScene: GameScene!

override func viewDidLoad() {

    super.viewDidLoad()

    if let view = self.view as! SKView? {

        // Load the SKScene from 'GameScene.sks'
        if let gameScene = GameScene(fileNamed: "GameScene")  {
            self.gameScene = gameScene
            gameScene = .aspectFill
            // Present the scene
            view.presentScene(gameScene)
        }
    }
}

func getCoords() {
    print("gameScene.rect.position \(gameScene.rect.position)")
}

关于ios - 获取Sprite在其他类(class)中的位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43053353/

10-12 01:53