-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject.tsx
51 lines (43 loc) · 1.41 KB
/
object.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import React, {forwardRef, useImperativeHandle, useRef} from 'react';
import {MeshProps, useFrame} from '@react-three/fiber/native';
import {BufferGeometry, Material, Mesh, NormalBufferAttributes} from 'three';
import * as THREE from 'three';
export interface IObjectRef {
getPosition: () => THREE.Vector3 | undefined;
}
interface IObject extends MeshProps {
type: 'box' | 'sphere' | 'torus' | 'plane';
isAnimationDisabled?: boolean;
}
const getGeometryByType = (type: IObject['type']) => {
switch (type) {
case 'box':
return <boxGeometry args={[0.75, 0.75, 0.75]} />;
case 'sphere':
return <sphereGeometry args={[0.5, 16, 16]} />;
case 'torus':
return <torusGeometry args={[0.3, 0.2, 16, 32]} />;
case 'plane':
return <planeGeometry args={[5, 5]} />;
default:
return null;
}
};
const Object = forwardRef<IObjectRef, IObject>(({type, isAnimationDisabled, ...rest}, ref) => {
const mesh = useRef<Mesh<BufferGeometry<NormalBufferAttributes>, Material | Material[]>>(null);
useFrame(() => {
if (mesh.current && !isAnimationDisabled) {
mesh.current.rotation.x = mesh.current.rotation.y += 0.01;
}
});
useImperativeHandle(ref, () => ({
getPosition: () => mesh.current?.position,
}));
return (
<mesh ref={mesh} {...rest}>
<meshStandardMaterial roughness={0.4}/>
{getGeometryByType(type)}
</mesh>
);
});
export default Object;