反应三根光纤useEffect、useState、three.Clock



我对R3F&在Three.js中,我很难将时间值作为一个简单着色器的变量。

我有一个GLSL着色器作为JavaScript文件,我想使用统一的u_time 更新时间值

我正在尝试使用React组件中的THREE.Clock来传递时间变量。当我在useEffect挂钩内控制台.log计时器时,我会将时间控制台记录为着色器所需的四舍五入值。但是,我不知道如何返回该值以在着色器中使用,作为u_time值。我的useEffect钩子里有什么东西丢了吗?

React组件代码

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;

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);
}
`;

感谢您的帮助:(

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>
);
};

然后调用画布内的组件:

const App = (props) => {
return (
<Canvas>
<ambientLight intensity={5} />
<spotLight position={[8, 3, 1]} penumbra={0.3} />
<Box />
</Canvas>
);
};

使用来自react三光纤的useFrame钩子,它有一个参数可以让你访问系统时钟

最新更新