function MovingBox()

in infrastructure/load-balancing-for-inference/components/play3d.tsx [7:83]


function MovingBox({ startPosition, delay = 0 }: { startPosition: [number, number, number], delay?: number }) {
  const ref = useRef<Group>(null)
  const [active, setActive] = useState(delay === 0)

  // Calculate direction vector once
  const [direction] = useState(() => {
    // Create normalized direction vector from center to startPosition
    const dirVector = new Vector3(startPosition[0], startPosition[1], 0).normalize()
    const speed = 0.04 + Math.random() * 0.03 // Adjusted base speed
    return [
      dirVector.x * speed,
      dirVector.y * speed,
      0.06 + Math.random() * 0.025, // Z movement
    ] as [number, number, number]
  })

  // Activate the cube after its delay
  useEffect(() => {
    if (delay > 0) {
      const timer = setTimeout(() => {
        setActive(true)
      }, delay)
      return () => clearTimeout(timer)
    }
  }, [delay])

  // Smooth movement in the animation loop
  useFrame((state, delta) => {
    if (!ref.current || !active) return

    // Cap delta to avoid large jumps on slow frames or tab switching
    const smoothDelta = Math.min(delta, 0.05)
    const moveSpeed = 45 // Tweak to taste

    // Frame-rate–independent movement
    ref.current.position.x += direction[0] * smoothDelta * moveSpeed
    ref.current.position.y += direction[1] * smoothDelta * moveSpeed
    ref.current.position.z += direction[2] * smoothDelta * moveSpeed
  })

  // If not active, render invisible cube to keep consistent instancing
  if (!active) {
    return (
      <group ref={ref} position={startPosition} visible={false}>
        <mesh>
          <boxGeometry args={[0.3, 0.3, 0.3]} />
          <meshBasicMaterial color="#FADF6B" />
        </mesh>
      </group>
    )
  }

  return (
    <group ref={ref} position={startPosition}>
      {/* Main 3D Box */}
      <mesh>
        <boxGeometry args={[0.3, 0.3, 1.3]} />
        <meshBasicMaterial
          color="#FADF6B"
          transparent={true}
          opacity={0.9}
          toneMapped={false}
        />
      </mesh>

      {/* Border Outline */}
      <lineSegments>
        <edgesGeometry attach="geometry" args={[new BoxGeometry(0.3, 0.3, 1.3)]} />
        <lineBasicMaterial 
          attach="material" 
          color="#e3a507"
          linewidth={3}
        />
      </lineSegments>
    </group>
  )
}