The Raycast function seems to be failing to detect the GlTF file in Three.js

After creating a binary gltf file in Blender and animating it with Mixamo, I am encountering an issue where it is not being detected on raycast. Despite trying numerous tutorials and solutions, I have been unable to resolve the issue.

const loader = new GLTFLoader();
let modelLoader = "/models/c2.glb";
let model, mixer, neck, waist;

loader.load(modelLoader, (gltf) => {
  model = gltf.scene;
  let fileAnimations = gltf.animations;
  model.traverse((o) => {
    // console.log(o);
    if (o.isBone && o.name === "mixamorigNeck") {
      neck = o;
    }
    if (o.isBone && o.name === "mixamorigSpine") {
      waist = o;
    }
    if (o.isMesh) {
      o.material.reflectivity = 1;
    }
  });

 document.addEventListener("click", (e) => raycast(e));
  document.addEventListener("touchend", (e) => raycast(e, true));

  function raycast(e, touch = false) {
    const raycaster = new THREE.Raycaster();
    const mouse = new THREE.Vector2();
    e.preventDefault();

    if (touch) {
      mouse.x = 2 * (e.changedTouches[0].clientX / window.innerWidth) - 1;
      mouse.y = 1 - 2 * (e.changedTouches[0].clientY / window.innerHeight);
    } else {
      mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
    }

    raycaster.setFromCamera(mouse, camera);

    const intersects = raycaster.intersectObjects(scene.children, true);
    console.log(scene.children);
    if (intersects.length > 0) {
      console.log("hi");}}

Although there are no errors, when I try to access the scene.children within the 'if (intersects){}' block by clicking on the 3D object, it returns an empty array. I also attempted to push the meshes into a new array for detection, but unfortunately, it did not work.

If anyone has any insight or solution to this problem, please lend your assistance!

Answer №1

Ray casting against a skinned mesh poses a problem because current versions of three.js like r128 struggle to calculate accurate bounding volumes for this type of 3D object. Proper bounding volumes are crucial for ray casting in order to detect early elimination.

To address this issue, one can manually define bounding volumes that effectively encompass the skinned mesh. One recommendation is to iterate through gltf.scene and assign the boundingSphere and boundingBox properties to the geometry of the skinned mesh.

For further details, visit the GitHub link: https://github.com/mrdoob/three.js/pull/19178

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

Ways to Extract HTML DOM Attributes using Jquery

I am working with an HTML DOM that is saved in a JavaScript Variable. I need to figure out how to retrieve its attributes. For example: <script> //element_html is ajax response var element_html = '<h1 style="" class="app-control " data-order ...

Creating a Dynamic Dropdown Menu in Rails 4

I am attempting to create a dynamic selection menu following this tutorial; however, I am encountering issues as the select statement does not seem to be updating. Below is the code snippet I currently have: #characters_controller.rb def new ...

Limiting the space character in a password field with regular expressions in JavaScript

Currently, I am facing the challenge of implementing a RegEx expression on a property within a model on an MVC website that I am currently developing. While I understand the individual components of the expression, I am struggling to combine them effectiv ...

What is the best way to incorporate a for loop in order to create animations with anime.js?

I am currently working on implementing a for loop to create a page loader using JQuery along with the animation framework anime.js var testimonialElements = $(".loader-animation"); for(var i=0; i < Elements.length; i++){ var element = ...

What could be causing the DATE_SUB function to fail in executing a MySQL query through Node.js?

I am encountering an issue with a datetime field in a MySQL database table on Planetscale. My goal is to subtract some time from the datetime value using the DATE_SUB function. While this operation works smoothly in the database console on Planetscale&apos ...

Issue with the rendering of a mirrored (flipped) three.js model

I have uploaded two *.obj models to my application. Although they appear to be identical, one of them is actually a mirrored version of the other. https://i.sstatic.net/yY0SM.png The first picture shows the original model, while the second one displays th ...

Pattern matching to verify a basic number within the range of [0-6]

const number = '731231'; const myRegex = /[0-6]/; console.log(myRegex.test(number)); Could someone provide some insight into this code snippet? In my opinion, the regular expression [0-6] should only match numbers between 0 and 6. However, i ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Optimizing logical expressions in C++

Can I assume in C, C++, JavaScript, or any other modern language that if I have the following code snippet... bool funt1(void) {…} bool funt2(void) {…} if (funt1() && funt2()) {Some code} ...I am guaranteed that both functions will be called, ...

The issue of `for` loop and `forEach` loop not functioning in EJS

I'm currently developing a To-Do App and facing difficulty with the POST request functionality. I've attempted using both a for loop and a forEach loop but none seem to be working. <% todos.forEach(item => { %> <li><%= item ...

How to use jQuery to center an overlay on a webpage

Need help with centering a jquery popup on a webpage? I'm struggling with positioning it in the middle of the page, regardless of site adjustments or resolution changes. Currently, I have it set to absolute positioning with CSS, but the issue is that ...

Error message encountered: React hydrate TypeError - the function __webpack_require_.i(...) is not recognized as a

I encountered a webpack TypeError while attempting to use hydrate() in my index.js file. Strangely, the error does not appear when I use ReactDOM.render() instead of hydrate. My intention behind using hydrate was for server-side rendering. src/index.js i ...

I encountered an error stating "angular not found" when attempting to dynamically load my Angular scripts

My Angular application is running smoothly. However, I found it tedious to include multiple script tags in my HTML documents every time. To simplify this process, I decided to create a small script that would automatically generate the necessary tags for m ...

Browser and contexmenu intersecting halfway

I have successfully implemented a custom context menu in my HTML project. It functions well, but I am facing an issue where half of the menu appears off-screen to the right. Is there a way to detect this and reposition the menu above the mouse pointer? He ...

Top method for transitioning FontAwsome stars class from regular to solid

How can I dynamically change the class of 5 stars of FontAwesome Icons from regular to solid based on a numeric variable level that ranges from 0 to 5? <template> <div id="five-stars"> <font-awesome-icon v-for="(inde ...

What is the best way to connect a JavaScript file to an HTML file in an Express app?

I have my NodeJS server set up with Express, utilizing Handlebars as the rendering engine. app.use(express.static(publicDirPath)) (...) app.engine("hbs",hbs({ extname: "hbs", defaultView: "main", layoutsDir: path.join(srcDirP ...

Require modification of JSON values in React Promise code

Looking to modify the data returned from a promise and wrap a link around one of the fields. Here is the React code: this.state = { medications: [], } queryMeds().then((response) => { this.setState({medications: response}); }); The response c ...

Is there a way to extract the timestamp in JavaScript from a string that includes the name of the timezone database?

Given the string: "2022/05/01 03:10:00", I am seeking to create a Date object with Chile's UTC offset. The challenge lies in the fact that due to Daylight saving time (DST), the offset changes twice annually. How can I obtain that Date obj ...

Examining the process through which an element attains focus

Scenario I am working on a Backbone application that has an event listener set up for focus events on a textarea. Since Backbone relies on jQuery events, my main concern revolves around jQuery focus events. Inquiry Is there a method to determine how an e ...

Include a stylesheet as a prop when rendering a functional component

Using Next.js, React, Styled JSX, and Postcss, I encountered an issue while trying to style an imported component for a specific page. Since the stylesheets are generated for a specific component at render time, I attempted to include custom styles for the ...