这可能是一个愚蠢的问题,但这是我的情况。
我有一个SKShapeNode
矩形在屏幕上从左到右依次如下:
// 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)
}
问题:如何从其他课程实时获取rect.position
。因此,每当我按下按钮时,我都会得到rect
的实际位置?
更新
在Ron的建议中,我更新了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
仅代表实际屏幕的一部分
答案 0 :(得分:1)
当您第一次转换到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)")
}