Convenient methods in Three.js for easily detaching and attaching character weapons within a scene

I'm currently facing challenges while developing a first-person shooter game using Three.js. I've encountered major glitches with THREE.SceneUtils.detach() and THREE.SceneUtils.attach(), and I'm uncertain if they are the appropriate methods to use.

In my game, my mech character has two guns positioned on either side. There is enough space between the guns for a small enemy to pass through without getting shot. To address this issue, I decided to make the guns 'lock on' and follow an enemy when it enters the center of the camera view. However, implementing this required me to refer to WestLangley's concept mentioned here: Three.js Rotate objects inside of moving Object3D to always face the camera

As a result, the revised portion of my code now looks like this:

autoTarget: function ( target ) {

    THREE.SceneUtils.detach( gunRootObject, characterRootObj, scene );
    gunRootObject.lookAt( target );
    gunRootObject.updateMatrix();


    this.direction = new THREE.Vector3( 0, 0, 1 );
    this.direction.applyQuaternion( gunRootObject.quaternion );
    THREE.SceneUtils.attach( gunRootObject, scene, characterRootObj);
}

Although this solution works successfully in half of the attempts, the other half results in both guns getting stuck at [0,0,0] concerning the characterRootObj.

Would you be able to point out any evident mistakes in my implementation? Is there a better approach to resolve the original problem I described?

Your suggestions and insights would be highly appreciated. Thank you!

Answer №1

After some careful consideration, I decided to take a completely new approach: I came to the realization that I can do without the lookAt() function if all I need is to rotate one object in relation to another. As a result, I have now opted to use basic trigonometry functions to determine the angle at which my guns should rotate based on the enemy's distance from the camera and other fixed reference points.

Given that the guns are stationary relative to the camera, I believe this solution will suffice for the time being.

Answer №2

I encountered a similar issue with that approach, where the function appeared to shuffle the children's positions, making it unreliable to loop through them. What ended up working for me was

    while (this.scalerSphere.children.length) {
        THREE.SceneUtils.detach(this.scalerSphere.children[0], this.scalerSphere, scene)
        this.scalerSphere.updateMatrixWorld()
    }

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

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Improving the Texture Quality of Canvas-Text in Three.js

How can I achieve sharpness for text in my drawings without using 3D text? Are there specific parameters, modes, or tricks that can be applied? I am using canvas to write text and symbols, creating something similar to label information. Thank you! ...

Properties of objects changing dynamically

<div id="bach">Bach</div> <div id="show">about composer</div> $(window).load(function(){ bach = {"bdate": 1685, "bplace": "Eisenach, Germany"} $("div").click(function(){ $("#show").text(this.id['bdate']); // ...

The Angular 2 service is not transmitting the POST data in the correct format, although it functions properly when transmitted through PostMan

When the POST data is transmitted from the Angular 2 service in this manner: const data = new FormData(); data.append('date', '12/01'); data.append('weight', '170'); return this.http.post(this.u ...

Three.js is failing to render within a specified div

My current project involves utilizing three.js to create a cube rendering. Despite the cube appearing on the screen, I am facing issues with getting it to display within the specified div element and in the desired style. HTML: <div id="render"> & ...

Generating an image in Fabric.js on a Node server following the retrieval of canvas data from a JSON

I've been trying to solve this problem for the past few days. In my app, users can upload two images, with one overlaying the other. Once they position the images and click a button, the canvas is converted to JSON format and sent to a node (express) ...

Is it necessary for me to develop a component to display my Navigation Menu?

After designing a Navigation menu component for desktop mode, I also created a separate side drawer component to handle variations in screen size. However, a friend of mine advised that a side drawer menu component may not be necessary. According to them ...

Issue with Firebase Cloud function not terminating despite receiving a 204 response code

Currently, I am developing a cloud function to manage server operations for a gaming panel. Everything seems to be functioning correctly except that after the request is completed, it fails to trigger the expected "data", "end", or "closed" events which ...

Why does xpath insist on choosing spaces instead of actual elements?

Here is a list of countries in XML format: <countries> <country> <code>CA</code> <name>Canada</name> </country> ... etc... </countries> I am looking to extract and loop through these nodes, so ...

Transforming an array in JavaScript into a JSON object

I'm currently working on creating a loop in JavaScript or jQuery to generate a new JSON object from an array. The goal is to convert an input JavaScript array into a desired format for the output. Here's the input array: INPUT: [ { ...

Why does jQuery only execute the very first condition or none at all if the first condition is false?

I'm trying to create a fixed button that, when clicked, scrolls to a specific section on the page. However, only the first condition seems to be working, and the other conditions are being ignored even when the first one is false. Can you help me figu ...

Troubleshooting my nodejs websocket chat for message sending glitches

The chat system is built on nodejs using websockets from socket.io library. While I have a client that also utilizes websockets from socket.io, I'm facing challenges in making the two communicate effectively. The issue seems to be with the client not ...

An error was encountered: An identifier that was not expected was found within the AJAX call back function

I am experiencing an issue while attempting to query an API. An Uncaught SyntaxError: Unexpected identifier is being thrown on the success part of my JQuery Ajax function. $(document).ready(function(){ $('#submitYear').click(function(){ let year ...

A step-by-step guide on importing several jpg texture files in THREE.js using obj and mtl files

Using THREE.js, it's simple to load tga or dds files as textures when loading obj + files. For example, in their obj + mtl example (): // Add tga texture files THREE.Loader.Handlers.add( /\.tga$/i, new THREE.TGALoader() ); However, what if you ...

The function is unable to accurately retrieve the state value

In my app, I have a component where I'm attempting to incorporate infinite scroll functionality based on a tutorial found here. export const MainJobs = () => { const [items, setItems] = useState([]); const [ind, setInd] = useState(1); const ...

Looking to display information in a column-by-column format using ng-grid within Angular JS

The data I have is structured like this: $scope.myStudentData = {"Moroni":{"id":"1","grade":"A"},"Tiancum":{"id":"2","grade":"B"}} However, the grid requires a different format: $scope.myGridOptions = [{"details":"id", "Moroni":"1", "Tiancum":"2"},{"det ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

Is it permissible to access an iframe directly by its name?

I recently came across some JavaScript code that directly accesses an iframe by its name, without using getElementById() or any other method. Surprisingly, this code seems to be functioning properly in browsers like Chrome, Firefox, IE10, and Safari for Wi ...

How to smoothly transition between different components in Angular 2 with scroll actions

I am looking to dynamically change components based on user scrolling. Here is the behavior I want to achieve: When the user reaches the end of a component, the next component should load When the user reaches the top of a component, the previous compone ...