Quicksilver
Quicksilver

Reputation: 2710

React three fiber using different materials on faces of cylinder

I am trying to create a cylinder with different colors on faces. I was able to do this using three.js. But while I am trying to implement this on r3f, I am not able to do this.

<Canvas frameloop="demand" camera={{ position: [75, 1, 0.1], zoom: 20 }}>
    <mesh>
      <cylinderGeometry />
      <meshBasicMaterial color={0xff0000} />
      <meshBasicMaterial color={0x00ff00} />
    </mesh>
    <OrbitControls />
  </Canvas>

I was able to do this on three.js by passing the materials as an array to the mesh. I don't know how to do this in r3f.

Codesandbox: here

Upvotes: 0

Views: 384

Answers (1)

Łukasz Daniel Mastalerz
Łukasz Daniel Mastalerz

Reputation: 2217

Try this

import "./styles.css";
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";

const colors = [0x00ff00, 0xff0000, 0x0000ff];

export default function App() {
  return (
    <div className="App">
      {/* eslint-disable */}
      <Canvas frameloop="demand" camera={{ position: [75, 1, 0.1], zoom: 15 }}>
        <mesh>
          <cylinderGeometry />
          {colors.map((color, index) => (
            <meshBasicMaterial
              key={index}
              attach={`material-${index}`}
              color={color}
            />
          ))}
        </mesh>
        <OrbitControls />
      </Canvas>
      {/* eslint-enable */}
    </div>
  );
}

https://codesandbox.io/p/devbox/cylinder-forked-yl47v5?file=%2Fsrc%2FApp.js%3A7%2C32

https://github.com/pmndrs/react-three-fiber/blob/484c6787bd4862d50a6fd38e436413f06f394fdb/docs/tutorials/v8-migration-guide.mdx#unified-attach-api

Upvotes: 2

Related Questions