If I have a function that spawns a cube right next to a previous cube whenever the user taps the screen and changes the color of the cubes as well, how can I make sure that each cube can become a random color and not the all the cubes become the same random color? I don't think I can use the same geometry for each cube because then it would inherit whatever material I originally gave to it. I want each cube that is spawned to select its own random color, not all the cubse select the same random color that it picks when tapping. I have a random color function, and it works. But if I spawn 5 cubes, and tap the screen, all 5 cubes become the same random color. But instead, I want each individual cube to be its own random color. I am using Swift, and SceneKit. Thanks for your help in advance.
func randomColor2() -> UIColor{
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
Right now I just say, inside of my touches began:
boxNodeMaterial.diffuse.contents = randomColor2
And I also call my createBox function which adds another box node beside the original box. I want this second box to pick it's own random color, not the same one as the original. I want this to continue for each box that is added. Box 1 can be red, green, or blue. Box 2 can be red, green, or blue, Box 3 and so forth. NOT Box 1, Box 2, Box 3 pick red for example and makes them all the same color.
You seem to create multiple SCNGeometry
, but all of them share the same material. This results in the problem you are describing: Changing the color of one material changes to color for all the boxes.
To avoid this, simply create a new SCNMaterial
each time you are creating a new box.
//Create a new, unique material for each box
let material = SCNMaterial()
material.diffuse.contents = randomColor2()
//Copy the box (or create a new one)
let newBox = oldBox.copy()
newBox.firstMaterial = material
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.