How to Control Character Position use KeyBoard key in React js

แชร์
ฝัง
  • เผยแพร่เมื่อ 20 ธ.ค. 2024

ความคิดเห็น • 1

  • @paradise_hope
    @paradise_hope  6 หลายเดือนก่อน

    import React, { Suspense, useRef, useEffect } from 'react';
    import { Canvas } from '@react-three/fiber';
    import { useGLTF, Html } from '@react-three/drei';
    import * as THREE from 'three'
    import { useProgress } from '@react-three/drei';
    const Loading = () => {
    const { progress } = useProgress();
    return Loading {progress.toFixed(2)} %;
    };
    const ModelViewer = () => {
    const gltf = useGLTF('/Soldier.glb');
    const modelRef = useRef();
    const [movementSpeed, setMovementSpeed] = React.useState(0.1);
    const handleKeyDown = (event) => {
    switch (event.key.toLowerCase()) {
    case 'w':
    modelRef.current.position.z -= movementSpeed;
    break;
    case 's':
    modelRef.current.position.z += movementSpeed;
    break;
    case 'a':
    modelRef.current.position.x -= movementSpeed;
    break;
    case 'd':
    modelRef.current.position.x += movementSpeed;
    break;
    default:
    break;
    }
    };
    useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    return () => {
    window.removeEventListener('keydown', handleKeyDown);
    };
    }, []);
    return (


    {gltf.scene && (
    )}

    );
    };
    export default ModelViewer;