如何在自定义 class 中从 viewcontroller 获取变量?

How to reach variable from viewcontroller in a custom class?

我需要在我的锚上附加一些东西。 我正在尝试在 class 的函数中执行此操作,但我在 viewcontroller.

中声明了此锚点

我的 class 无法识别此锚点。我如何找到这个锚点?

viewController.swift:

import UIKit
import RealityKit
import Combine

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let gameAnchor = AnchorEntity(plane: .horizontal)
        arView.scene.addAnchor(gameAnchor)

        //generate random width en distance
        let randomDistance = Double.random(in: 0.07...0.25)
        let randomWidth = Double.random(in: 0.01...0.05)

        //make a new platform
        let newPlatform = Platform(width: randomWidth, heigth: 0.1, depth: 0.05, distance: randomDistance)
        newPlatform.makePlatform()
    }
}

我的class:

import Foundation
import RealityKit

class Platform {
    var width: Double = 0.05
    var heigth: Double = 0.1
    var depth: Double = 0.05
    var distance: Double = 0.1

    init(width: Double, heigth: Double, depth: Double, distance: Double) {
        self.width = width
        self.heigth = heigth
        self.depth = depth
        self.distance = distance
    }

    func makePlatform() {
        let platformMesh = MeshResource.generateBox(width: Float(width), height: 0.1, depth: 0.05)
        let platformMaterial = SimpleMaterial(color: .red, isMetallic: false)
        let newPlatform = ModelEntity(mesh: platformMesh, materials: [platformMaterial])
        newPlatform.position.x = Float(distance)
        newPlatform.position.y = 0.05

        //append it to my anchor
        ///gameAnchor.addChild(newPlatform)
    }
}

在 newPlatform.makePlatform() 之后添加

 gameAnchor.addChild(newPlatform.platform)

并使平台成为一个 class 变量,而不是 makePlatform 方法的本地变量。您还需要在视图控制器中将 newPlatform 设为 class 变量,而不是 viewDidLoad 的本地变量。