Guide to moving a 3D model and initiating animation in threejs when a key is pressed

In the midst of a project where a person (gltf object) walks based on key presses, I have successfully updated the object position accordingly.

However, I'm encountering difficulty in rotating the object when the left/right keys are pressed and ensuring that the object continues to walk in that direction.

I have included the code for reference below:

import { OrbitControls } from '../assets/js/OrbitControls.js';
import { GLTFLoader } from '../assets/js/GLTFLoader.js';
import { OBJLoader } from '../assets/js/OBJLoader.js';

// Various functions and initializations
function init(){
    // Code block for initializing the scene, camera, lights, loaders, and objects
}

function loadDoor(){
    // Loading the door object with necessary transformations
};

function loadMan(){
    // Loading the animated man object with animation playback
}

function getAlternateTiles() {
    // Generating alternate tiles pattern on the floor
}

function getFloorMaterialByImage() {
    // Applying image texture to the floor material
}

// Animation loop
function animate() {
    // Calling render function and updating the walking man
}

function updateMan(){
    // Updating the position and rotation of the walking man based on keyboard input
}

function render() 
{
    // Rendering the scene with camera view
}

A link showcasing the animation used in the project can be found here.

Your assistance with this matter is greatly appreciated. Thank you!

Answer №1

I made some adjustments to my updateMan() function so that the camera always focuses on the person model. Additionally, the relativeCameraOffset should now be in the opposite direction of the current camera position.

Please review the code provided below.

If you notice any mistakes, please let me know.

function updateMan(){

    var delta = clock.getDelta(); // seconds.
    var rotateAngle = Math.PI / 2 * delta; 

    var moveDistance = 150 * delta; // 100 pixels per second
    var rotateAngle = Math.PI / 2 * delta;   // pi/2 radians (90 degrees) per second
    
    if ( keyboard.pressed("a") ){
        man_walk.rotateOnAxis(new THREE.Vector3(0,1,0), rotateAngle);
    }
    if ( keyboard.pressed("d") ){
        man_walk.rotateOnAxis(new THREE.Vector3(0,1,0), -rotateAngle);
    }
    if ( keyboard.pressed("w") ){
        man_walk.translateZ(moveDistance);
        mixer.update(delta);
    }
    var relativeCameraOffset = new THREE.Vector3(0,250,-600);
    var cameraOffset = relativeCameraOffset.applyMatrix4( man_walk.matrixWorld );
    camera.position.x = cameraOffset.x;
    camera.position.y = cameraOffset.y;
    camera.position.z = cameraOffset.z;
    camera.lookAt(man_walk.position);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Populate a dropdown menu using JSON data

I am working with an SQLite table that has columns for id and name. I have created a JSON array of rows from the autocomplete.php page. Now, I am trying to populate a dropdown list in my select element using this JSON data by utilizing jQuery and JavaScrip ...

In React production, the use of .map as a function is unavailable

While my express react app build runs smoothly locally with the map function, the transition to production triggers an error stating that 'map' is not a function. The error specifically points to the line declaring 'let returnlist'. Be ...

Next.js: Dealing with special characters in YouTube video API snippet titles

Trying to find the perfect video snippet title without any special characters. Accessing the API: https://www.googleapis.com/youtube/v3/search, along with specifying snippet. The current output for snippet.title is as follows: I'M GONNA CARRY ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...

Utilizing Multiple MongoDB Connections in a Node.js Application

I am facing an interesting challenge in my Node.js project where I need to connect multiple MongoDB databases. Let me share with you my current setup and the issue that is causing me some trouble. Node Version: v6.12.1 Express.js Version: 4.16.2 Mongoos ...

Develop a React component that organizes an array based on specified index ranges in JavaScript

Imagine having an array structured like this: let numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19]; I am interested in creating a React component that displays the elements of the array in groups of 10. The desired output should look like t ...

Images cannot be shown until they have been uploaded

My issue involves a menu that loads an external file (form) on the same page, and for the menu, I am utilizing a specific function for menu styling. Custom Menu Function function getXmlHttp() { try { return new ActiveX ...

Include additional data in the FormData object before sending it over AJAX requests

Currently, I am utilizing AJAX to store some data. The primary concern I have is figuring out how to incorporate additional information into the FormData object along with what I already have. Below is the function that I'm using. Could you assist me ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

passing commands from a chrome extension to a content script

I want to set up a hotkey that will activate a function in my content script. The content script (main.js) is run when the page loads from my popup.js file. I've included the command in my manifest.json and I can see in the console log that it is tri ...

Tips for excluding files in a webpack configuration for a Vue application during the production build

I am attempting to remove an Html file named "dev.html" from the final product build. What configurations do I need to make in webpack for this? I understand that rules need to be applied, but where exactly do I need to configure them? Below is a snippe ...

I'm having trouble with my bootstrap dropdown and I've exhausted all of my options trying to fix it based on my current understanding

My dropdown menu is not working despite adding all necessary Bootstrap CDN and files along with the jQuery script. Even with the table being handled by JavaScript, the button does not respond when clicked repeatedly. I suspect the issue lies within the han ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...

Receive an HTTP POST request within JavaScript without using Ajax in Symfony 4.1

Searching for a way to handle an event triggered by a PHP post, not through Ajax. I would like to show a spinner when the form is posted using PHP. In JavaScript, it's easy with code like this: $(document).on({ ajaxStart: function() { $('#p ...

Is there a way to achieve the same task with Ajax?

Hey there, I am new to the world of JavaScript and AJAX. I have been reading about how to convert a client-side JavaScript variable into a server-side PHP variable by using AJAX. Can someone please provide me with a code snippet using AJAX for this purpose ...

When an Ajax post request is made, the data being sent is appended to the JSON response

Having a dilemma with my ajax call: $.ajax({ url: '/assets/functions.php', type: 'POST', data: { "functionCall": "get-uploads", "type": type }, dataType: 'json', success: function (data ...

Having difficulty launching the sapper app in production mode

Having trouble starting my sapper project in production mode. When running npm run start, the following output appears on the console: niklas@Niklass-iMac project-name % npm run start > [email protected] start /Users/niklas/path/to/project > node _ ...

What is the best way to show a filtered list using a state that was created with useState in React?

Check out my code in CodeSandbox, consisting of 4 divs categorized as "Book" and "Article". There are buttons at the top to toggle between displaying all divs, only books, or only articles. However, clicking on any button currently shows all divs and gives ...

Tips for identifying tablet devices using the deviceDetector module in AngularJS

Having an issue with a Samsung Tablet. I need to display certain content for mobile devices, but not tablets. Device detection results: - isMobile(): true - isTablet(): false Here is the detailed data from the module: {"raw":{"userAgent":"Mo ...