Struggling with Three.js raycasting issues

My mesh is positioned at the origin.

var textureCanvas = new THREE.CanvasTexture( imageCanvas );
textureCanvas.repeat.set( 4, 4 );
textureCanvas.wrapS = THREE.RepeatWrapping;
textureCanvas.wrapT = THREE.RepeatWrapping;

var materialCanvas = new THREE.MeshBasicMaterial( { map: textureCanvas } 
);

var geometry = new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(-4,-4,0),
    new THREE.Vector3(-4,4,0),
    new THREE.Vector3(4,4,0),
    new THREE.Vector3(4,-4,0),
);

geometry.faces.push(                    
    new THREE.Face3(3, 1, 0),
    new THREE.Face3(3, 2, 1)
);

var vertexMappings = [];
vertexMappings[0] = new THREE.Vector2(0,1);
vertexMappings[1] = new THREE.Vector2(0,0);
vertexMappings[2] = new THREE.Vector2(1,0);
vertexMappings[3] = new THREE.Vector2(1,1);
var vm = vertexMappings;

geometry.faceVertexUvs[ 0 ] = [];
geometry.faceVertexUvs[0][0] = [ vm[3], vm[1], vm[0] ];
geometry.faceVertexUvs[0][1] = [ vm[3], vm[2], vm[1] ];                

meshCanvas = new THREE.Mesh( geometry, materialCanvas );
meshCanvas.rotation.x = - Math.PI / 3;
meshCanvas.rotation.z = - Math.PI / 2.5;

meshCanvas.scale.set( 80, 80, 80 );

scene.add( meshCanvas );

There is also a line intersecting the mesh. Originally, it passed through the origin, but I adjusted its position (refer to github issue below).

var linegeo = new THREE.Geometry();
linegeo.vertices.push(
    new THREE.Vector3(55, 300, 0),
    new THREE.Vector3(-10, -300, 32)
);

scene.add(linemesh);

I am trying to find the intersection point between the line and the mesh, but the intersection result is always empty:

getInersectionPosition(linemesh, meshCanvas);


function getInersectionPosition(linemesh, meshCanvas) {
    linemesh.updateMatrixWorld();
    meshCanvas.updateMatrixWorld();

    var p1 = linemesh.geometry.vertices[0].clone(),
    p2 = linemesh.geometry.vertices[1].clone();

    p1.applyMatrix4(linemesh.matrixWorld);
    p2.applyMatrix4(linemesh.matrixWorld);

    //console.log(`p1: ${JSON.stringify(p1)}, p2: ${JSON.stringify(p2)}`);
    //console.log(`canvas position: ${JSON.stringify(meshCanvas.position)}`);

    var raycaster = new THREE.Raycaster(p1, p2);
    raycaster.linePrecision = 10;

    //var intersections = raycaster.intersectObjects([meshCanvas]);
    var intersections = raycaster.intersectObjects(scene.children, true);

    if (intersections.length > 0)
        console.log(`intersections: ${ intersections.length}`);
}

Complete example: https://jsfiddle.net/mribbons/103wwsda/

Could the issue be related to this? https://github.com/mrdoob/three.js/issues/11449

The raycaster.intersectObjects() method seems to have issues, with very large distance values (2.7 million) compared to the sphere radius (~450).

https://github.com/mrdoob/three.js/blob/dev/build/three.js#L9761

intersectsSphere: function ( sphere ) {
    var distance = this.distanceToPoint( sphere.center )

    return distance <= sphere.radius;

},

Answer №1

After reviewing the issue, it turns out that raycaster requires both a point and a normal for proper operation. The problem can be solved by implementing the following code snippet:

var normalVector = new THREE.Vector3();

normalVector.subVectors(point2, point1).normalize();

var rayCaster = new THREE.Raycaster(point1, normalVector);

var intersections = rayCaster.intersectObjects(scene.children, true);

if (intersections.length > 0)
    console.log(`Number of intersections: ${ intersections.length}`); // displays "Number of intersections: 2"

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

Positioning an element in the center of another using JQuery

Greetings! I am currently working with some elements that look like this: <div id="one">content</div> <div id="two">content</div> These elements are followed by another set of elements (without any parent, placed directly after th ...

Steps to retain localStorage data while redirecting to another external webpage

Encountering an issue with saving localStorage data across redirects. See the code snippet below: // Invoke newSitelogin(). Save response(credentials) in localStorage. Redirect to new URL. newSitelogin({ uuid, password }) .then(() => { window.ope ...

Dynamic Bootstrap Tab menu slider with movable functionality when the limit is reached

I am facing an issue with the tabs menu on my website. The tabs menu items can vary between 2 or 3 to even 20 or more. When the number of navigation items exceeds 10, they automatically drop to the second line, which you can see here. However, I don' ...

What is the best way to incorporate a dropdown menu into existing code without causing any disruption?

I've come across this question multiple times before, but I still haven't found a suitable answer or solution that matches my specific situation. (If you know of one, please share the link with me!) My goal is to create a basic dropdown menu wit ...

What steps should be taken to ensure that the onmouseover and onmouseout settings function correctly?

The Problem Currently, I have a setup for an online store where the shopping cart can be viewed by hovering over a div in the navigation menu. In my previous prototype, the relationship between the shoppingTab div and the trolley div allowed the shopping ...

I'm experiencing difficulty accessing the correct identification number for my questions on the website

Hi, I'm currently developing a website using Meteor where users can post questions and receive answers. I want to implement a feature that allows users to delete their own questions. When I try to directly pull the ID of the question and delete it, it ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

Using JavaScript (AJAX), learn the process of incorporating XML data within HTML files

I'm relatively new to HTML and I'm attempting to create a self-contained HTML page that includes all necessary CSS, data, and JavaScript within the file itself. While I understand that this will result in a rather messy HTML document, it is essen ...

Utilizing FontAwsome Icons within a CSS2DObject using VueJS

As an aspiring coder, I am determined to display a FontAwsome User Icon similar to the example here within a VueJS component. I have diligently attempted to replicate the same example showcased in this codesandbox, exploring the two approaches recommended ...

Using async method in controller with NestJS Interceptor

I am seeking a way to capture both the result and any potential errors from an asynchronous method within a controller using an interceptor. When an error is thrown, the interceptor can respond accordingly. However, I am struggling to figure out how to tri ...

Switch between visibility of objects with toggle button

I have set a background image on the body, and positioned a large box, footer, navigation bar, and header above it. In order to add functionality to slide these elements up and down, I've created two buttons with classes 'slideUp' and &apos ...

Use AppScript to exclude the first row (which contains the column names) when filtering a table

Considering the limitations of Google Sheets with the ImportRange function, I decided to develop an AppScript as a replacement. Although I am new to JavaScript, here is what I have so far: function My_ImportRange() { var clearContent = SpreadsheetApp.ge ...

What is the best way to move between websites or pages without having to reload the current page using a selector?

Have you ever wondered how to create a webpage where users can navigate to other websites or pages without seeing their address, simply by selecting from a drop-down menu? Take a look at this example. Another similar example can be found here. When visit ...

Dealing with performance issues in VueJS and Vuetify's data-table component, especially when trying to implement

In my VueJS and Vuetify project, I encountered an issue. I am trying to create a table with expandable rows for displaying orders and their associated products. The table needs to show at least 100 rows of orders on one page. To achieve this, I utilized th ...

Geometric structures in the style of Minecraft: Hexagonal Voxel Design

I'm attempting to create a hexagonal map by following the example at . Is there a way to generate hexagons instead of cubes? Using the first option from the manual resulted in creating a hexagonal mesh and positioning it. However, the second option ...

Error in JSON Format Detected in Google Chrome Extension

Struggling with formatting the manifest for a simple Chrome extension I'm developing. I've been bouncing back and forth between these two resources to try and nail down the correct syntax: https://www.sitepoint.com/create-chrome-extension-10-mi ...

Is there a way to trigger the bootstrap datetimepicker when a custom button is clicked, while also storing the selected value in a hidden textbox

When the ADD button is clicked, a datetimepicker should open. After selecting a value from the datetimepicker, it should be saved in the textbox with ID #myTextBox. <div> <input id="myTextBox" type="text" ng-model="c" data-provide="datepicker ...

Having trouble with fetch() not working in Next.JS while securing API Routes with auth.js

Currently, I am working on a project that involves user authentication using auth.js in next.js. The main goal is to create an API that retrieves specific user information from a MongoDB Database. The website itself is secured with middleware in next.js. I ...

Remove user from firebase with Admin SDK

I need help understanding how to remove a user from my admin panel using the Firebase Admin SDK. When attempting to delete a user, I encountered this error: Uncaught (in promise) ReferenceError: uid is not defined at eval (ManageCustomer. ...

Tips on enlarging the header size in ion-action-sheet within the VueJS framework of Ionic

Recently I started using Vue along with the ionic framework. This is a snippet of code from my application: <ion-action-sheet :is-open="isActionSheetOpen" header="Choose Payment" mode="ios" :buttons="buttons&qu ...