How to properly (dynamically) change color of a mesh into group?

I have a model:

<group ref={group} {...props} dispose={null} onDoubleClick={e => {e.stopPropagation(); clickHandler(e)}}>
    <mesh geometry={nodes.Mesh7_Group3_Group2_Group1_G_2016_Lexus_LX570__1_1_Lexus_LX570_.geometry} material={nodes.Mesh7_Group3_Group2_Group1_G_2016_Lexus_LX570__1_1_Lexus_LX570_.material} position={[-72.7, 0.53, 4.83]} rotation={[1.83, -0.26, 0]} scale={2.05} />
    <mesh geometry={nodes.Mesh740_black1_Group8_Group1_G_2016_Lexus_LX570__1_1_Lexus_LX57.geometry} material={materials.black_plastic_matt} position={[-72.75, 0, 4.83]} rotation={[1.83, 0.24, -0.13]} scale={2.05} />
    <mesh geometry={nodes.Mesh468_plasstik_r1_Group8_Group1_G_2016_Lexus_LX570__1_1_Lexus.geometry} material={nodes.Mesh468_plasstik_r1_Group8_Group1_G_2016_Lexus_LX570__1_1_Lexus.material} position={[-72.75, 0, 4.83]} rotation={[1.83, 0.24, -0.13]} scale={2.05} />
</group>

By this function I can change color of a clicked target, but it triggers changing color of a material generally and all parts with this material changing its color.

const clickHandler = (e: any) => { 
                e.object.material.color = {r: 0, g: 1, b: 0} 
      }

I also tried to edit my meshes:

From:

<mesh geometry={nodes.toyota_alphard039.geometry} material={materials.black_plastic_gloss} rotation={[Math.PI / 2, 0, 0]}/>

to:

<mesh geometry={nodes.toyota_alphard039.geometry} material={materials.black_plastic_gloss} rotation={[Math.PI / 2, 0, 0]}>
    <meshBasicMaterial color="red" />
</mesh>

It forced me to an idea of creation a function that will adding into mesh the node <meshBasicMaterial color="red" />

How to implement it correctly?

1 answer

  • answered 2022-05-04 11:35 benkov

    to change one element color , you need to clone its material first, apply changes to the new material, and then add the material to the clicked element. Something like this

    const clickHandler = (e: any) => { 
           new_material = e.object.material.clone();
           new_material.color.setRGB(0,1,0);
           e.object.material = new_material;
           e.object.material.needsUpdate = true
           // and need to call your render function to apply changes to scene
           }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum