Having trouble getting a Three.js invisible plane to work correctly with raycaster.intersectObject?

I've been experimenting with creating draggable objects similar to this interesting example:

The array objectMoverLines contains the objects that should be draggable.

To incorporate a plane into my scene, I utilized the following code:

plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(500, 500, 8, 8), new THREE.MeshBasicMaterial({color: 0x248f24, alphaTest: 0}));
plane.visible = false;
scene.add(plane);

An issue arises within the onDocumentMouseDown function. Strangely, when the plane's visibility is set to false (plane.visible = false), at a certain point intersectsobjmovers does not get populated. However, setting the plane's visibility to true resolves the issue (though it obstructs the view with a large plane):

function onDocumentMouseDown(event) {
    // Object position movers
    var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
    vector.unproject(camera);

    raycaster.set( camera.position, vector.sub( camera.position ).normalize() );
    var intersectsobjmovers = raycaster.intersectObjects(objectMoverLines);
    if (intersectsobjmovers.length > 0) {
        console.log('clicking an object mover');
        // Disable the controls
        controls.enabled = false;
        // Set the selection - first intersected object
        objmoverselection = intersectsobjmovers[0].object;
        // Calculate the offset
        var intersectsobjmovers = raycaster.intersectObject(plane);

        // At this point, intersectsobjmovers does not include any items, even though
        // it should (but it does work when plane.visible is set to true...)

        offset.copy(intersectsobjmovers[0].point).sub(plane.position);
    } else {
        controls.enabled = true;
    }
}

In addition, here is what I currently have under the onDocumentMouseMove function:

function onDocumentMouseMove(event) {
    event.preventDefault();

    mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;

    // Get 3D vector from 3D mouse position using 'unproject' function
    var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
    vector.unproject(camera);

    // Set the raycaster position
    raycaster.set( camera.position, vector.sub( camera.position ).normalize() );

    if (objmoverselection) {
        // Check the position where the plane is intersected
        var intersectsobjmovers = raycaster.intersectObject(plane);
        // Reposition the object based on the intersection point with the plane
        objmoverselection.position.copy(intersectsobjmovers[0].point.sub(offset));
    } else {
        // Update position of the plane if need
        var intersectsobjmovers = raycaster.intersectObjects(objectMoverLines);
        if (intersectsobjmovers.length > 0) {
            // var lookAtVector = new THREE.Vector3(0,0, -1);
            // lookAtVector.applyQuaternion(camera.quaternion);
            plane.position.copy(intersectsobjmovers[0].object.position);
            plane.lookAt(camera.position);
        }
    }

    requestAnimationFrame( render );
}

Answer №1

Check out this code snippet:

let plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(500, 500, 8, 8), 
   new THREE.MeshBasicMaterial( {
       color: 0x248f24, alphaTest: 0, visible: false
}));

scene.add(plane);

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

Tips on stopping or unbinding a previous $watch in AngularJS

Currently, I am utilizing $watch in a dynamic manner which results in the creation of another $watch on each call. However, my intention is to unbind the previous $watch. $scope.pagination =function(){ $scope.$watch('currentPage + numPerPage', ...

Utilize a directive to showcase information stored within the scope

Struggling to grasp the concept of directives and encountering a bug along the way. To see my example in action, check out the codepen I've created here In my scope called "movies," I have 3 movie titles that I want to display using a directive. va ...

Positioning a Three.js static CSS2DObject with respect to the camera's perspective

I am currently working on a unique program visualizer that utilizes Three.js to showcase various aspects of a program to the user. One crucial feature of this visualizer is allowing users to click on specific objects to view additional information about th ...

Learn the process of showcasing database content on a webpage with an interactive feature that enables users to choose and access additional details

Apologies if this question has been asked before, I have searched for a solution but my web development knowledge is limited. To better understand my issue, you can visit the site at 000freewebhost by following this link: In summary, I am trying to select ...

Master the art of navigating the Windows Sound Recorder with the power of JavaScript

I am creating a project that involves controlling the Windows sound recorder for tasks such as starting, stopping, and saving recordings. Is there a way to do this without displaying the recorder window? I would appreciate any assistance in solving this. ...

Is it possible to prevent a page from reloading upon form submission in Svelte Kit without using preventDefault?

Whenever a user performs an action, like logging in to the app, I want to show a toast message for a few seconds. The login form is located at /login/page.svelte, with database interaction handled by /login/page.server.js. A writable store is used to save ...

"Resizing issue with multiple Highcharts not being resolved after selecting a new option from

Is there a way to resize multiple Highcharts on a webpage by clicking a button? When attempting to update the last chart using a dropdown menu and then clicking the resize button, an error message stating Uncaught TypeError: Cannot read property 'refl ...

Ways to maintain hover functionality when the submenu is visible

My website features a simple table that displays devices and their characteristics. A condensed version of the table can be found in the link below. import "./styles.css"; import { SubMenu } from "./SubMenu"; const subMenuSlice = <S ...

What is preventing me from creating accurate drawings on canvas?

I'm currently working on a paint application and facing an issue. When I place the painting board on the left side of the screen, everything works fine and I can draw without any problems. However, when I move it to the right side of the screen, the m ...

Previewing an uploaded image before submitting with FileBase64: A step-by-step guide

How can I implement a preview for an uploaded image before submitting the form? I have the upload functionality working but I would like to add a preview feature for the image. Below is the code snippet I am currently using: const [shop, setShop] = us ...

The global variable remains unchanged within an ajax request

Here is the code I am working with: In developing this code, I referenced information about the window variable from here <script> $(window).on("load", function() { function myForeverFunc(){ ...

Utilize Ajax.ActionLink on a DIV by incorporating data from the Model

Although there are similar questions on this topic already, they do not address the specific issue of using values from the model as arguments for the controller. Make DIV containing AJAX ActionLink clickable Div as Ajax.ActionLink Take a look at the fo ...

Sending properties within components using #createElement in React-Router is a convenient way to pass data locally

Have you ever wondered where the parameters Component and props are coming from in the React-Router documentation? // Here is the default behavior function createElement(Component, props) { // ensure all props are passed in! return <Component {... ...

Why doesn't ngSubmit function inside a modal?

I am experiencing an issue where my submit button is not activating the ng-click angular directive, and I cannot seem to identify the cause. Most people who faced a similar problem did not have their submit button placed inside their form, but I am confi ...

Steps to prevent specific links from being clickable in React Native's webview component

In my React Native app, I am utilizing the react-native-webview component to display blog posts. The code I have implemented is straightforward, but my goal is to restrict the webview to only show content from the blog section of the website, preventing us ...

Ways to display a tooltip on a listbox that can be moved

My ASPX page contains the following control: <asp:ListBox ID = "X" runat="Server" CssClass = "listbox"></asp:ListBox> I need to display a tooltip on each list item, as they are movable and their positions can be c ...

Revise the reply within ExpressJS

I need help with editing the response to a request in Express. When the request is made via XHR, I want to encapsulate the body inside a JavaScript object. This way, different parts of the page can be accessed individually within the JavaScript object, suc ...

Switching images through onmouseover, onmouseout, and onclick interactions

I have two images named img1 and img2. Here is my code: function roll(id, img_name, event_name, img_id) { var state ; if(event_name == 'mouseover') { state = false;rollover();} else if(event_name == 'mouseout') { ...

Assigning a Value to a Select Option in a Dynamically Generated Form

I've developed a dynamic form that includes a dropdown menu. I would like this dropdown to display fiscal weeks, and to achieve this, I need to implement a loop within a TypeScript function. form.ts - <div class="col-md-9" [ngSwitch]="field.type ...

What is the best way to send a Node.js variable to the inner part of a Pug script tag?

I am attempting to pass a variable from my Node.js backend to a Pug template and then use that variable inside a JavaScript script tag within the Pug file. Here's a snippet of my Node.js code: app.get('/profile', function (req, res) { var ...