Skip to content

Instantly share code, notes, and snippets.

@Densyakun
Last active March 19, 2023 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Densyakun/7292570cc4c04a6486105fc41974870e to your computer and use it in GitHub Desktop.
Save Densyakun/7292570cc4c04a6486105fc41974870e to your computer and use it in GitHub Desktop.
import * as React from 'react'
import * as THREE from 'three'
import { useFrame } from '@react-three/fiber'
import { Instance, Instances, useGLTF } from '@react-three/drei'
export default function Tracks() {
let r = 0
const { scene } = useGLTF('https://raw.githubusercontent.com/Densyakun/assets/main/railway/track/rail-50n-1067.gltf')
const instancedMeshesRef = React.useRef<(THREE.InstancedMesh | null)[]>([])
useFrame(({ }, delta) => {
r += delta
instancedMeshesRef.current?.forEach(instancedMesh => instancedMesh && (
instancedMesh.position.y = Math.sin(r)
))
})
return (
<>
{scene.children.map((child, index) => <Instances
key={index}
ref={el => instancedMeshesRef.current[index] = el}
limit={1000}
range={30 * 30}
geometry={(child as THREE.Mesh).geometry}
material={(child as THREE.Mesh).material}
receiveShadow
castShadow
>
{[...Array(30)].flatMap((_, z) =>
[...Array(30)].map((_, x) => <Instance
key={z * 30 + x}
position={(child as THREE.Mesh).position.clone().add(new THREE.Vector3(x * 3, 0, z))}
/>)
)}
</Instances>)}
</>
)
}
import * as React from 'react'
import * as THREE from 'three'
import { useFrame } from '@react-three/fiber'
import { Gltf } from '@react-three/drei'
export default function Tracks() {
let r = 0
const itemsRef = React.useRef<THREE.Object3D[]>([])
useFrame(({ }, delta) => {
const y = Math.sin(r += delta)
itemsRef.current.forEach(el => el.position.y = y)
})
return (
<>
{[...Array(30)].flatMap((_, z) =>
[...Array(30)].map((_, x) => <group ref={(el: THREE.Group) => itemsRef.current[z * 30 + x] = el}>
<Gltf
key={z * 30 + x}
src="https://raw.githubusercontent.com/Densyakun/assets/main/railway/track/rail-50n-1067.gltf"
position={[x * 3, 0, z]}
receiveShadow
castShadow
/>
</group>)
)}
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment