refactor: elegance

This commit is contained in:
cha0s 2022-03-24 09:00:58 -05:00
parent d5f11c83d0
commit 9b8d9f9d29
2 changed files with 18 additions and 40 deletions

View File

@ -66,6 +66,12 @@ function Play() {
clearInterval(inputHandle); clearInterval(inputHandle);
}; };
}, [selfEntity, socket]); }, [selfEntity, socket]);
// Initial camera position snap.
useEffect(() => {
if (selfEntity) {
selfEntity.camera.realPosition = selfEntity.camera.position;
}
}, [selfEntity]);
return ( return (
<> <>
<Renderable /> <Renderable />

View File

@ -1,11 +1,9 @@
import {Vector} from '@avocado/math'; import {Vector} from '@avocado/math';
import {usePropertyChange} from '@avocado/react';
import {RoomUi} from '@avocado/topdown'; import {RoomUi} from '@avocado/topdown';
import { import {
React, React,
useEffect,
useFlecks, useFlecks,
useRef,
useState,
} from '@flecks/react'; } from '@flecks/react';
import { import {
@ -14,48 +12,22 @@ import {
} from '../../../../hooks'; } from '../../../../hooks';
import Hotbar from './hotbar'; import Hotbar from './hotbar';
const focus = (element) => {
element.focus();
};
const PlayUi = () => { const PlayUi = () => {
const flecks = useFlecks(); const {config: {'@humus/app': {resolution}}} = useFlecks();
const ref = useRef();
const room = useRoom(); const room = useRoom();
const selfEntity = useSelfEntity(); const selfEntity = useSelfEntity();
const [position, setPosition] = useState([0, 0]);
const [domScale, setDomScale] = useState([1, 1]);
// Handle camera changes.
useEffect(() => {
if (!room || !selfEntity) {
return undefined;
}
// Initial snap camera to position.
selfEntity.camera.realPosition = selfEntity.camera.position;
const onCameraRealOffsetChanged = () => {
setPosition(Vector.scale(selfEntity.camera.realOffset, -1));
};
const onCameraViewSizeChanged = () => {
setDomScale(Vector.div(flecks.get('@humus/app.resolution'), selfEntity.camera.viewSize));
};
onCameraRealOffsetChanged();
onCameraViewSizeChanged();
selfEntity.camera.on('realOffsetChanged', onCameraRealOffsetChanged);
selfEntity.camera.on('viewSizeChanged', onCameraViewSizeChanged);
return () => {
const {camera} = selfEntity;
if (camera) {
camera.off('realOffsetChanged', onCameraViewSizeChanged);
camera.off('viewSizeChanged', onCameraViewSizeChanged);
}
};
}, [flecks, room, selfEntity]);
// Focus.
useEffect(() => {
if (ref.current) {
ref.current.focus();
}
});
return ( return (
// eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
<div ref={ref} tabIndex="0"> <div ref={focus} tabIndex="0">
<RoomUi domScale={domScale} position={position} room={room} /> <RoomUi
domScale={Vector.div(resolution, usePropertyChange(selfEntity?.camera, 'viewSize', [0, 0]))}
position={Vector.scale(usePropertyChange(selfEntity?.camera, 'realOffset', [0, 0]), -1)}
room={room}
/>
{selfEntity && <Hotbar selfEntity={selfEntity} />} {selfEntity && <Hotbar selfEntity={selfEntity} />}
</div> </div>
); );