ib9*_*b95 2 javascript glsl reactjs react-three-fiber
我是 R3F 和 Three.js 的新手,我很难将时间值作为简单着色器的变量。
我有一个 GLSL 着色器作为 JavaScript 文件,我想使用统一的 u_time 更新时间值
我试图在我的 React 组件中使用 THREE.Clock 传递时间变量。当我在 useEffect 挂钩内 console.log 计时器时,我将时间控制台记录为舍入值,因为着色器需要它。但是我不确定如何返回这个值以在我的着色器中使用,作为 u_time 值。我的 useEffect 挂钩中是否缺少某些内容?
反应组件代码
import React, { useRef, useEffect, useState } from "react";
import { Canvas, useThree, useFrame } from "@react-three/fiber";
import { vertexShader, fragmentShader } from '../Shaders/Shader';
const ShaderPlane = (props) => {
const [value, setValue] = useState(0);
const mesh = useRef()
const time = new THREE.Clock();
useEffect(() => setInterval(() => setValue(time.getElapsedTime().toFixed(1)), 1000), []);
console.log(value)
return (
<Canvas>
<ambientLight intensity={5} />
<spotLight position={[8, 3, 1]} penumbra={0.3} />
<mesh
{...props}
ref={mesh}
scale={[4,4,4]}
>
<planeBufferGeometry attach="geometry" />
<shaderMaterial
uniforms={{
u_time: { value: value },
}}
vertexShader={vertexShader}
fragmentShader={fragmentShader}
/>
</mesh>
</Canvas>
)
}
export default ShaderPlane;
Run Code Online (Sandbox Code Playgroud)
Shader.js代码
export const vertexShader = `
void main()
{
// v_uv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position * 1.0, 1.0 );
//turning the vec3 into a vec 4 by adding 1.0 to the end
}
`;
export const fragmentShader = `
uniform float u_time;
void main()
{
vec3 color = vec3((sin(u_time) + 1.0)/2.0, 0.0, (cos(u_time) + 1.0)/2.0);
gl_FragColor = vec4(color, 1.0);
}
`;
Run Code Online (Sandbox Code Playgroud)
感谢你的帮助 :)
R3F 挂钩只能在 Canvas 元素内部使用,因为它们依赖于上下文。只需在组件内调用 useFrame 挂钩即可。
const Box = (props) => {
const ref = useRef();
useFrame((state) => {
const time = state.clock.getElapsedTime();
time.current += 0.03;
ref.current.rotation.y += 0.01;
ref.current.rotation.x += 0.001;
ref.current.material.uniforms.u_time.value = state.clock.elapsedTime;
});
return (
<mesh ref={ref} {...props}>
<boxGeometry attach="geometry" />
<shaderMat attach="material" />
</mesh>
);
};
Run Code Online (Sandbox Code Playgroud)
然后在画布内调用您的组件:
const App = (props) => {
return (
<Canvas>
<ambientLight intensity={5} />
<spotLight position={[8, 3, 1]} penumbra={0.3} />
<Box />
</Canvas>
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4616 次 |
| 最近记录: |