Creating a bond between an object and a bone in Three.js

Is it possible to connect mesh to bone in a 3D animation? For instance, if I have an animated .js character, can I attach a weapon to its hand?

Answer №1

With just a few clever tricks applied to the Bone and Object3D prototype, it's entirely feasible. Because bones are derived from Object3D, they have the capability to have children, allowing us to easily attach a mesh to any bone.

Notably, the SkinnedMesh will trigger updateMatrixWorld() exclusively on non-Bone children, while Bone children will undergo an update(). Furthermore, every bone initiates an update() for all of its children, regardless of their bone status. The following code snippets alter this standard functionality:

// Enhance bone update function to update its world matrix as well
// Consider performing this action solely on skeletons where necessary, rather than all bones
var update = THREE.Bone.prototype.update;
THREE.Bone.prototype.update = function(parentSkinMatrix, forceUpdate) {
    update.call(this, parentSkinMatrix, forceUpdate);
    this.updateMatrixWorld( true );
};

// Introduce a dummy update function to the Object3D prototype
// This enables any Object3D instance to be a child of a Bone
THREE.Object3D.prototype.update = function() {};

// Implement buffalo creation...

// Generate a mesh and attach it to a selected bone
var mesh = new THREE.Mesh( new THREE.SphereGeometry(20), new THREE.MeshNormalMaterial() );

var bone = buffalo.bones[5];
bone.add(mesh);

Answer №2

In the latest version of Three.js, which is Version 68, handling bone hierarchies has been simplified with a new approach. The bone hierarchy can now be accessed directly from the children of the SkinnedMesh without needing to modify any internal functions.

The process now involves locating the specific bone in the list of children and attaching an object to it as follows:

player.children[0].add(testObj);

It's worth noting that if your model includes a bone hierarchy (e.g., from a blender export), this structure is mirrored in Three.js. If the targeted bone has a parent bone, the code would look something like this:

player.children[0].children[1].add(testObj);

Answer №3

        const skeletonModel = scene.getObjectByName("skeletonModel");   
        loader.load("AttachmentModel", (object) => {
            object.name = "attachedModelToBone";
        
            skeletonModel.children[x].skeleton.getBoneByName("boneForAttachingObject").add(object);
        });

This solution is effective for my needs.

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

Here is the code I have written to implement a date-picker event that retrieves specific records based on the selected date

I'm struggling with inserting a question here. Can someone provide assistance? $query = ("SELECT orders.customer_id, customer.name, customer.email, customer.address, customer.phone_number, orders.product_id, orders.total_units, orders.total_price, or ...

Best practices for executing an asynchronous forEachOf function within a waterfall function

I've been working with the async library in express js and I'm encountering an issue when using two of the methods alongside callbacks. The variable result3 prints perfectly at the end of the waterfall within its scope. However, when attempting t ...

Every time I attempt to load a .fbx file, I encounter the error message indicating that the variable "worldMatrices" is

ReferenceError: circleVars is not defined Traceback: parseCircle@file:///C:/Users/Guillermo%20P/Proyectos/Blank%20Null%201.0/blankNull/10.0.0.3/js/FBXLoader2.js:1384:10 parse@file:///C:/Users/Guillermo%20P/Proyectos/Blank%20Null%201.0/blankNull/10.0.0.3/js ...

Upgrading from version 122 to 123 of Three.js causes the shadows to disappear on a custom layer within Mapbox

While working on adding a custom layer to mapbox using three.js, following the official example from mapbox, I encountered an issue with shadows not displaying as expected in version 123, despite working perfectly in version 122. I carefully reviewed the r ...

Merge the values of an object's key with commas

I'm dealing with an array of objects that looks like this: let modifiers = [ {name: "House Fries", price: "2.00"}, {name: "Baked Potato", price: "2.50"}, {name: "Grits", price: "1.50"}, {name: "Nothing on Side", price: "0.00"} ] My goal is to con ...

Ways to verify if the fetch variable contains data

function Login() { const [email, setEmail] = useState(""); const [password, setpassword] = useState(""); const [users, setUser] = useState([]); function login() { fetch( "http://116.202.231.219:8069/Restaurant/Login_Updated?Cont4=" + ...

Instructions on how to invoke a function defined in a JavaScript module (type=module) from an HTML document

I've been facing difficulties with using JavaScript modules... I have an HTML file and a JS module. In the javascript file, I have a function defined that I want to call from my HTML page. Here is my code: index.html <html> <head> < ...

Determine the character's position in an input field by tracking mouse movements

I am in need of a way to determine the position of a character in an input field based on mouse movement. For example, if the input field contains the value 'abcde' and I hover my mouse over the character 'a', the position should be ...

Accessing image from Azure with the assistance of Graph API

I need assistance with retrieving a profile picture using the Microsoft Azure API. The code snippet provided below demonstrates my attempt to do so. private getProfilePicture(bearerToken: string, tenantId: string): void { let command = CommandHelper. ...

What could be causing a case where this.props.posts is undefined in React and Redux

Recently, I attempted to follow a React and Redux tutorial on a blog. However, when working with the PostList component, I encountered an error related to the reducer binding. My main goal was simply to render the renderPost function by calling the reducer ...

Updating the contents of one specific div without affecting all other divs with the same class

Below is the HTML code snippet in question: <a class="btn test-btn test-btn-1"> <span>Content 1</span> </a> This particular code block appears multiple times on the page. The number at the end of test-btn- is dynamically generat ...

Encountering Axios CanceledError while attempting to forward a POST request using Axios

While attempting to relay a POST request from an express backend to another backend using axios, I encountered an axios error stating "CanceledError: Request stream has been aborted". Interestingly, this issue does not arise when dealing with GET requests. ...

When using React and React Router v6, make sure to implement a 404 status code response for unmatched routes

When it comes to managing unmatched routes with React Router, I have a solid understanding: <Routes> {/* Public routes */} <Route exact path="/" element={<Home />} /> // Other routes... {/* Error routes */} ...

Converting CSV data to a specific file type using Reactjs

My goal is to transform JSON data into CSV format, then convert that CSV data into a CSV file, and finally upload the file onto Firebase. Although I have successfully converted the JSON to CSV, I am currently facing difficulties in converting the data in ...

Issue with referencing Asmx web service

I am struggling to properly reference my web service method with JavaScript on my client page. I keep receiving an error message that says "CalendarHandler is not defined". <%@ WebService Language="C#" CodeBehind="~/App_Code/CalendarHandler.cs" Class ...

In what way are these columns altering their layout without the use of JavaScript?

While I was searching for a solution to organize content based on screen size, I came across this website. The layout of the site changes depending on the size of the browser window. When I resize my browser or view the site on a phone, the large image at ...

Retrieve the attribute of the clicked element by utilizing the on click event handler

Within my HTML, there is a page displaying approximately 25 thumbnails, each with a like button in this specific format: <input type="button" class="btn btn-primary btn-small" id="likeBtn" data-id="545206032225604" value="Like"> It's important ...

What is the best way to assign an identifier to a variable in this scenario?

script.js $('a').click(function(){ var page = $(this).attr('href'); $("#content").load(page); return false; }); main.html <nav> <a href="home.html">Home</a> <a href="about.html">About</a> < ...

What is the proper way to retrieve multiple property values stored in a property name using getJSON

I'm having trouble getting multiple languages to work in my code. Could someone assist me and provide guidance on how to write multiple choices for the property name language? When I input code like this to display only Dota 2 games in English, every ...

Using jQuery, you can easily apply a new class to a div when it is

I'm currently facing an issue with adding a class of "active" to a div upon clicking it using jQuery. My goal is to apply the css class of active in order to give the button a distinct color (or the hover effect.) Unfortunately, I have been unsuccess ...