Three.js Character Control with Animation

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

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

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

    import React, { Suspense, useRef, useEffect } from 'react';
    import { Canvas, useFrame } from '@react-three/fiber';
    import { useGLTF, Html, useAnimations, Grid } from '@react-three/drei';
    import * as THREE from 'three'
    import { useProgress } from '@react-three/drei';
    import { OrbitControls } from '@react-three/drei';
    const Loading = () => {
    const { progress } = useProgress();
    return Loading {progress.toFixed(2)} %;
    };
    const Character=()=>{
    const {scene,animations} = useGLTF('/Soldier.glb');
    const group=useRef()
    const modelRef = useRef();
    const { actions } = useAnimations(animations, modelRef);
    console.log("Action",actions)
    //const {actions,name}=useAnimations(animations,group)
    const [movementSpeed, setMovementSpeed] = React.useState(0.01); // Adjust movement speed as needed
    useFrame(()=>{
    //actions.Idle.play()
    })
    const handleKeyDown = (event) => {
    switch (event.key.toLowerCase()) {
    case 'w':
    actions.Walk.play()
    modelRef.current.position.z -= movementSpeed;
    break;
    case 's':
    actions.Walk.play()
    modelRef.current.position.z += movementSpeed;
    break;
    case 'a':
    actions.Walk.play()
    modelRef.current.position.x -= movementSpeed;
    break;
    case 'd':
    actions.Walk.play()
    modelRef.current.position.x += movementSpeed;
    break;
    default:
    break;
    }
    };
    const handleKeyUp = (event) => {
    switch (event.key.toLowerCase()) {
    case 'w':
    case 's':
    case 'a':
    case 'd':
    actions.Walk.stop();
    break;
    default:
    break;
    }
    };
    useEffect(() => {
    actions.Idle.play()
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup',handleKeyUp)
    return () => {
    window.removeEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup',handleKeyUp)
    };
    }, []);
    return(
    {scene && (
    )}
    )
    }
    const ModelViewer = () => {
    return (





    );
    };
    export default ModelViewer;