简体   繁体   中英

How to use a SKScene as texture for SCNSphere?

I want to create a sphere of green color with a red point on its surface. One of the most efficient way that I found was to use a SKScene as the texture of the sphere with the desired properties, and display it as a whole inside a frame in SwiftUI. After I run the code I get a sphere with plain white color.

My code is:

import SwiftUI
import SceneKit
import SpriteKit
import UIKit

//SKScene containing the point 

class material: SKScene{

let point = SKShapeNode(circleOfRadius: 0.5)
override func didMove(to view: SKView) {
    backgroundColor = SKColor.green
    point.fillColor = SKColor.red
    point.position = CGPoint(x: 100, y: 100)
    physicsWorld.gravity = CGVector.zero
    addChild(point)

  }
}

//SCNScene containing the sphere 

 struct SceneKitView: UIViewRepresentable {

  func makeUIView(context:            UIViewRepresentableContext<SceneKitView>) -> SCNView {
    let sceneView = SCNView()
    sceneView.scene = SCNScene()
    sceneView.allowsCameraControl = true
    sceneView.autoenablesDefaultLighting = true
    sceneView.backgroundColor = UIColor.white
    sceneView.frame = CGRect(x: 0, y: 10, width: 0, height: 1)


    let sphere = SCNSphere(radius: CGFloat(2))

    sphere.firstMaterial?.diffuse.contents = material()

    let spherenode = SCNNode(geometry: sphere)
    spherenode.position = SCNVector3(x: 10.0, y: 10.0, z: 10.0)
    sceneView.scene?.rootNode.addChildNode(spherenode)

    return sceneView
}

 func updateUIView(_ uiView: SCNView, context:     UIViewRepresentableContext<SceneKitView>) {

}

  typealias UIViewType = SCNView
}

//SwiftUI code

struct ContentView: View {
 var body: some View {

    SceneKitView()
        .frame(width: 300, height: 300)

  }
}

Please help me with this problem.

diMove was never called.

if you really call it, the sphere gets green....

 let material = Material()

    sphere.firstMaterial?.diffuse.contents = material

    material.didMove(to: SKView())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM