TheKalashnikov
TheKalashnikov

Reputation: 391

Toggle materials/textures in an instance in react-three-fiber

I have an instance using Drei library with a plane geometry. According to a state, I would like to display different materials for each instance:

enter image description here

What would be the best way to do that?

Retained solution: Instanced Attributes

As mentionned by @Bhushan Wagh, the idea is to store the texture state inside a geometry attribute. Then, you can access this data in the shaders in order to apply a custom logic. You can follow his codesandbox for the R3F solution, or this one for the drei instance solution.

Investigated solutions

  1. Having 2 distinct instances (one for the colored material, one for the image texture):

it's ok when we have only 2 states, but what if we have like 10 possible states? (What would be the best solution in this case?)

  1. Represent a plane with a boxGeometry and display the proper face according to the state

It's also only working when we only have 2 states and are in 2D

Upvotes: 1

Views: 1598

Answers (1)

Bhushan Wagh
Bhushan Wagh

Reputation: 56

I don't think you need to change the material if you just wanna toggle between plain color and texture. You can do this doing some changes in shader of material where you pass the vec4 to gl_fragColor in fragment shader based on the state, you can pass the state as attribute to the mesh, since you using instanced mes you can use the instancedAttribute. I had the codesandbox for solution for using different textures on each object of instanced mesh so I made a changes in that code to solve your problem ( or at least what I think is solution) https://codesandbox.io/s/toggle-texture-of-instanced-mesh-ptcvbb You can toggle state of each plane by clicking on it. and I think this should work even with more than 2 states, you can represent the states with number and based on number you can select particular texture from texture array passed as uniform.

Upvotes: 1

Related Questions