The issue with Three JS is that concentrating on the avatar's perspective while it moves is not functioning properly

I am currently delving into the world of Three JS as a novice in 3D programming. Following a tutorial from the book , I am working on a game where an avatar navigates through trees. My current challenge involves getting the camera to continuously focus on the back of the avatar while it moves within the 3D environment.

To achieve this, I have created a marker attached to the avatar for the camera to target. However, when I move the avatar, the camera does not follow along with it.

Below is my code snippet:

var scene = new THREE.Scene();
var aspectRatio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, aspectRatio, 1, 10000);
camera.position.z = 500;

// Additional code for creating avatar, trees, and animation

marker.add(camera); // Focus the camera on the marker.

function animate() {
    requestAnimationFrame(animate);

    // Additional code for animation logic
    
    renderer.render(scene, camera);
}

document.addEventListener('keydown', function (event) {
    var code = event.keyCode;

    // Movement controls and animations based on key presses
});
animate();
body {
    margin: 0px;
}
canvas {
    width: 100%;
    height: 100%;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>First 3D avatar game</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r125/three.min.js"></script>
</head>
<body>
</body>
</html>

If you can identify what is causing the issue in my code and provide suggestions on how to rectify it, I would greatly appreciate it!

Answer №1

When it comes to object nesting, precision is key. Here's the current setup:

Marker
├── Avatar
└── Camera

As you can see, Avatar and Camera are nested under Marker. However, if you only update the position of Avatar without touching Marker, the entire structure won't move as expected.

If your goal is to have the camera follow the movement, you should actually update the position of Marker instead. This way, both Avatar and Camera will move together seamlessly, just like in the example below:

var scene = new THREE.Scene();
var aspectRatio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, aspectRatio, 1, 10000);
camera.position.z = 500;

// More code here...
body {
    margin: 0px;
}
canvas {
    width: 100%;
    height: 100%;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>First 3D avatar game</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r125/three.min.js"></script>
</head>
<body>
</body>
</html>

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

Use JavaScript to swap out images

How can I change the image arrow when it is clicked? Currently, I have this code snippet: http://codepen.io/anon/pen/qEMLxq. However, when the image is clicked, it changes but does not hide. <a id="Boton1" class="button" onClick="showHide()" href="j ...

Angular's ngRoute is causing a redirect to a malformed URL

Currently, I am in the process of developing a single-page application using AngularJS along with NodeJS and Express to serve as both the API and web server. While testing locally, everything was working perfectly fine. However, after cloning the repositor ...

Code Wizard

I am currently working on a project to develop an HTML editor. How it Needs to Function Elements Inside: Text Area - Used for typing HTML as text Iframe - Displays the typed HTML as real [renders string HTML to UI] Various Buttons Functionality: When ...

What is the best way to interpret JSON using JavaScript?

Do you know how to access and read JSON in JavaScript? Here is an example of a JSON string: {"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile ...

What is the best way to ensure that FileReader's onload event has finished before proceeding?

Currently, I am facing an issue with the synchronous execution of the onLoad method using FileReader. The problem arises when the onLoad method does not execute synchronously with the rest of the code. Below are two functions that exemplify this issue: ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...

Exploring the capabilities of Three.js obj-loader within a React application

My initial attempt involved importing directly from node_modules, as well as using a minified library, but both failed. I then tried an older version of the Three.js library without any modifications. Even after using an example with an imported three-obj- ...

Exploring the Modularity of Post Requests with Node.js, Express 4.0, and Mongoose

Currently, I am immersed in a project that involves utilizing the mean stack. As part of the setup process for the client-side, I am rigorously testing my routes using Postman. My objective is to execute a post request to retrieve a specific user and anot ...

What is causing the 'Invalid Hook Call' error to appear in React?

I have recently started learning React and I am currently working on converting a functional component into a class component. However, I encountered an error message that says: Error: Invalid hook call. Hooks can only be called inside of the body of a fu ...

Implementing the Context API with React Router: using version '^5.2.0' of react-router-dom and version '17.0.2' of React

I am currently struggling to retrieve the user value from my Header component using the Context API, but unfortunately it is returning as undefined. Below is my code snippet. import React, { createContext, useEffect, useState } from "react"; exp ...

Download function in Express.JS failing to retrieve file

I have been working on a Node.JS server using Express to generate and download PDFs based on user input. Previously, I used the <form action=""> method to call my API, but switched to Axios due to Netlify not supporting NuxtAPI. The program ...

Choose a Range of DOM Elements

My challenge is to select a range of DOM elements, starting from element until element. This can be done in jQuery like this: (Source) $('#id').nextUntil('#id2').andSelf().add('#id2') I want to achieve the same using JavaScr ...

Utilize JavaScript libraries in a TypeScript project

Looking to integrate a payment system called iyzico into my project. The iyzico payment library can be found here. However, there are no types available for it. How can I utilize this library in my Node.js TypeScript Express backend project? I attempted t ...

Stop background scrolling with CSS overlay menu

Is there a way to create a CSS overlay menu that prevents the main content it covers from scrolling when the menu is active? In other words, I want users to be able to scroll through the menu without affecting the background content. I've managed to ...

Reactivity in Vue 3 doesn't seem to be activated when called from within a class instance

Link to Codepen: https://codepen.io/codingkiwi_/pen/XWMBRpW Let's consider a scenario where you have a class: class MyClass { constructor(){ this.entries = ["a"]; //=== example change triggered from INSIDE the class === setTi ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

Tips for ensuring that the callback method waits for the completion of Google Markers creation

While developing my app with the Google Maps library, I encountered an issue either due to an unexplainable delay in creating markers or an unseen asynchronous problem. Here is a breakdown of the situation: The code retrieves the locations of Electric Cha ...

Switch image on click (toggle between pause and play buttons)

Having some difficulty setting up a 3D audio player in A-Frame where the pause and play button images need to change depending on whether the audio is playing or not. Interested in seeing my code in action? Check it out here. ...

Leveraging the state feature in react-router-dom's Redirect

I have been utilizing the instructions provided by react-router-dom's Redirect in my project. Currently, I have a component that displays the code snippet below: return <Redirect to={{ pathname: '/login', state: { previousPath: path } } ...

IE7 is failing to execute jQuery and Javascript code

The code snippet below is encountering compatibility issues with IE7, despite functioning properly on IE 8, IE 9, and all other browsers. Even the inclusion of alert("something"); does not yield the desired outcome - curiously, another script is executing ...