Materials
Materials are a fundamental part of 3D graphics. They define the appearance of 3D objects and are used to create realistic lighting effects. Materials can be applied to Render
components to change the appearance of 3D objects. They accept a wide range of properties to control the appearance of the material.
The useMaterial
hook returns a StandardMaterial
instance. This is useful if you need to create materials and apply them to Render
components.
import { useMaterial } from '@playcanvas/react/hooks'
const RedBox = () => {
const material = useMaterial({ diffuse: 'red' });
return (
<Entity>
<Render type="box" material={material} />
</Entity>
)
}
In the example below, we're using the useMaterial
hook to create a material and applying it to a Render
component. We also add a onClick
event to the Entity
to change the material properties when the cube is clicked.
- Demo
- Code
import { useState } from 'react';
import { Entity } from '@playcanvas/react';
import { Render } from '@playcanvas/react/components';
import { useMaterial } from '@playcanvas/react/hooks';
const orange = {
diffuse: 'orange',
emissive: 'black'
};
const red = {
diffuse: 'red',
emissive: 'gray'
};
const powderblue = {
diffuse: 'powderblue',
emissive: 'orange'
};
const materials = [orange, red, powderblue];
export const Materials = () => {
const [materialProps, setMaterialProps] = useState(orange);
const material = useMaterial(materialProps);
const onRequestRandomColor = () => {
const randomMaterial = materials[Math.floor(Math.random() * materials.length)];
setMaterialProps(randomMaterial);
};
return (
<Entity onClick={onRequestRandomColor} position={[0, 0.5, 0]}>
<Render type="box" material={material} />
</Entity>
);
};
Materials have a wide range of properties that can be used to control the appearance of the material. You can find the full list of properties here.