I want to compare the colors of two model entities (spheres). How can i do it? The method i'm currently trying to apply is as follows
case let .color(controlColor) = controlMaterial.baseColor, controlColor == .green { // Flip target sphere colour if let targetMaterial = targetsphere.model?.materials.first as? SimpleMaterial, case let .color(targetColor) = targetMaterial.baseColor, targetColor == .blue { targetsphere.model?.materials = [SimpleMaterial(color: .green, isMetallic: false)] // Change to |1⟩ } else { targetsphere.model?.materials = [SimpleMaterial(color: .blue, isMetallic: false)] // Change to |0⟩ } }
This method (baseColor) was deprecated in swift 15.0 changes to 'color' but i cannot compare the value color to each other.👾
Hello @SuyashBel
The .color
property of SimpleMaterial is of type SimpleMaterial.BaseColor
(which is itself a typealias for PhysicallyBasedMaterial.BaseColor
), which is a struct with two properties: .texture
and .tint
. You can use this .tint
property to check the color of your ModelEntity
.
Here is some example code to get you started:
// Keep a reference to the blue SimpleMaterial you created when you first insantiated your Entity let blueMat: SimpleMaterial = .init(color: .blue, isMetallic: false) let greenMat: SimpleMaterial = .init(color: .green, isMetallic: false) // This function toggles the material of an Entity func toggleMaterial(entity: Entity) { let isBlue = isBlue(entity: entity) guard var model = entity.components[ModelComponent.self] else { return } if isBlue { model.materials[0] = greenMat } else { model.materials[0] = blueMat } entity.components.set(model) } // Check if an Entity is blue by comparing the tint of its material with the tint of your cached material. func isBlue(entity: Entity) -> Bool { guard let model = entity.components[ModelComponent.self], let modelMat: SimpleMaterial = model.materials.first as? SimpleMaterial else { return false } // NOTE: modelMat.color.tint == .blue will always fail, because UIColor.blue has a different color space than SimpleMaterial.color.tint return modelMat.color.tint == blueMat.color.tint }