Added movement and rotation

This commit is contained in:
2023-11-14 16:35:52 +01:00
parent 157dd3a51b
commit 7ed084a815

View File

@@ -27,14 +27,13 @@ let mixer, clip, action, playerModel;
loader.load( './src/objects/models/player.gltf', function ( gltf ) {
playerModel = gltf;
gltf.scene.scale.set(0.2,0.2,0.2);
gltf.scene.rotateOnWorldAxis(new THREE.Vector3(1,0,0), MathUtils.degToRad(90));
//gltf.scene.rotateOnWorldAxis(new THREE.Vector3(1,0,0), MathUtils.degToRad(-90));
alignGround(ground, gltf.scene);
scene.add( gltf.scene );
mixer = new THREE.AnimationMixer( gltf.scene );
clip = THREE.AnimationClip.findByName( gltf.animations, 'Walk' );
action = mixer.clipAction( clip );
action.play();
}, undefined, function ( error ) {
@@ -55,6 +54,7 @@ MOVEMENT
const PLAYER_SPEED = 0.015;
const playerDirection = new THREE.Vector3(0, 0, 0);
const playerRotation = new THREE.Quaternion();
// Events to listen keyboard inputs
document.addEventListener('keydown', handleKeyDown);
@@ -62,14 +62,15 @@ document.addEventListener('keyup', handleKeyUp);
//Managing keys
function handleKeyDown(event) {
action.play();
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
playerDirection.y = -1; // Up
playerDirection.y = 1; // Up
break;
case 'ArrowDown':
case 'KeyS':
playerDirection.y = 1; // Back
playerDirection.y = -1; // Back
break;
case 'ArrowLeft':
case 'KeyA':
@@ -83,6 +84,7 @@ function handleKeyDown(event) {
}
function handleKeyUp(event) {
action.stop();
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
@@ -103,6 +105,13 @@ function updatePlayerPosition() {
const delta = playerDirection.clone().multiplyScalar(PLAYER_SPEED);
playerModel.scene.position.add(delta);
camera.position.add(delta);
const angle = Math.atan2(playerDirection.x, -playerDirection.y);
const targetRotation = new THREE.Quaternion();
targetRotation.setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
playerRotation.slerp(targetRotation, 0.1);
playerModel.scene.setRotationFromQuaternion(playerRotation);
playerModel.scene.rotateOnWorldAxis(new THREE.Vector3(1,0,0), MathUtils.degToRad(90));
}
function animate() {