0

我需要在我的锚点上附加一些东西。我试图在我的类的一个函数中做到这一点,但我在我的视图控制器中声明了这个锚。

这个锚在我的班上不被认可。我如何到达这个锚点?

视图控制器.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()
    }
}

我的课:

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)
    }
}
4

1 回答 1

1

在 newPlatform.makePlatform() 之后添加类似

 gameAnchor.addChild(newPlatform.platform)

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

于 2019-12-13T18:08:43.083 回答