use-downkeys.ts 836 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { getDownKeys } from "@/core/hook/use-global-vars";
  2. import { mergeFuns } from "@/utils/shared";
  3. import { Vector3 } from "three";
  4. import { shallowRef, watch } from "vue";
  5. export const getMoveDirectrionByKeys = () => {
  6. const { var: keys, onDestroy: onDownDestory } = getDownKeys();
  7. const direction = shallowRef<Vector3>()
  8. const stopWatch = watch(keys, (keys) => {
  9. let dire = new Vector3()
  10. if (keys.has('a')) {
  11. dire.setX(-1)
  12. }
  13. if (keys.has('d')) {
  14. dire.setX(1)
  15. }
  16. if (keys.has('w')) {
  17. dire.setY(1)
  18. }
  19. if (keys.has('s')) {
  20. dire.setY(-1)
  21. }
  22. if (dire.x || dire.y) {
  23. direction.value = dire.normalize()
  24. } else {
  25. direction.value = undefined
  26. }
  27. }, { deep: true });
  28. return {
  29. direction,
  30. onDestory: mergeFuns(stopWatch, onDownDestory)
  31. }
  32. }