Skip to content

Instantly share code, notes, and snippets.

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/f0caec26e5d999e8960ffe0b4cbf76c1 to your computer and use it in GitHub Desktop.
Save Densyakun/f0caec26e5d999e8960ffe0b4cbf76c1 to your computer and use it in GitHub Desktop.
import * as React from 'react'
import * as THREE from 'three'
import { PerspectiveCamera, OrthographicCamera, OrbitControls, MapControls } from '@react-three/drei'
import { OrbitControls as OrbitControlsImpl, MapControls as MapControlsImpl } from 'three-stdlib'
import { useSnapshot } from 'valtio'
import { state } from './MapCameraSwitch'
type CameraName = 'default' | 'map' | undefined
export default function SwitchableCameras() {
const { showingMapCamera: viewIsMap } = useSnapshot(state)
const defaultCamera = React.useRef<THREE.PerspectiveCamera>(null!)
const mapCamera = React.useRef<THREE.OrthographicCamera>(null!)
const orbitControls = React.useRef<OrbitControlsImpl>(null!)
const mapControls = React.useRef<MapControlsImpl>(null!)
const [changeCamera, setChangeCamera] = React.useState<CameraName>()
const [cameraTarget, setCameraTarget] = React.useState(new THREE.Vector3(0, 0, 0))
React.useEffect(() => {
if (changeCamera !== 'default') {
orbitControls.current?.target.copy(cameraTarget)
orbitControls.current?.update()
}
if (changeCamera !== 'map') {
mapControls.current?.target.copy(cameraTarget)
mapControls.current?.update()
}
setChangeCamera(undefined)
}, [cameraTarget])
React.useEffect(() => {
if (changeCamera === 'default') setCameraTarget(orbitControls.current.target)
else if (changeCamera === 'map') setCameraTarget(mapControls.current.target)
}, [changeCamera])
return (
<>
<PerspectiveCamera
ref={defaultCamera}
makeDefault={!viewIsMap}
position={[0, 0, 10]}
/>
<OrthographicCamera
ref={mapCamera}
makeDefault={viewIsMap}
position={[0, 100, 0]}
rotation={[0, 0, -90]}
zoom={50}
/>
<OrbitControls
ref={orbitControls}
camera={defaultCamera.current}
enabled={!viewIsMap}
onChange={() => {
setChangeCamera('default')
}}
/>
<MapControls
ref={mapControls}
camera={mapCamera.current}
enabled={viewIsMap}
onChange={() => {
setChangeCamera('map')
}}
/>
</>
)
}
npm i -D three-stdlib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment