Control the movement of an item within a threejs environment using your mouse

I am struggling to move an object within a threejs scene as I am unable to select the object when clicking with the mouse. I attempted to adapt the code provided in this link (https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_draggablecubes.html) for my own application, but unfortunately, it did not work in my specific case.

My question is: is the function provided in the code correct?

Additionally, are the camera position and rotation set correctly in the complete code provided?

function onDocumentMouseDown(event) {
    console.log("function onDocumentMouseDown");
    console.log(mouse.x, mouse.y);
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( objects );

    if (intersects.length > 0) {
        alert("finally");
        console.log(intersects[0]);
        intersects[0].object.material.transparent = true;
        intersects[0].object.material.opacity = 0.1;
        SELECTED = intersects[0].object;
        var intersects = raycaster.intersectObject( plane );
        if ( intersects.length > 0 ) {
             offset.copy( intersects[ 0 ].point ).sub(plane.position);
        }
    }
}

To access the complete code, please visit https://github.com/lohmanndouglas/Simulador.git

Answer №1

The issue arose from utilizing other DIV elements on my webpage. To resolve this, it was essential to convert clientX and clientY to the relative coordinates of the specific DIV being used.

I made adjustments to the code where I was updating the mouse.x and mouse.y variables.

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

Instead, I modified it to:

   mouse.x = ( (event.clientX - event.target.getBoundingClientRect().left) /event.currentTarget.width ) * 2 - 1;
   mouse.y = - ( (event.clientY - event.target.getBoundingClientRect().top) / event.currentTarget.height ) * 2 + 1;

Implementing this adjustment successfully resolved the issue for me.

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

The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/ Interestingly, the same script does not seem to work when embedded in an HTML document: <!DOCTYPE html> <html lang="en"> <head> & ...

Navigating through different views in a Vue application using Vue Router directly from Vuex actions

Currently, I am in the process of developing a web application using Vue 2.x and Vuex 2.x. In this project, I need to retrieve some data from an external source via an http call. If this call fails, my objective is to redirect to a different page. GET_PET ...

A guide on retrieving real-time data from PHP using Ajax

Being new to Ajax, I am struggling to grasp how to retrieve changing variable values from php. Below is the code snippet that I have been working on: <?php $pfstatetext = get_mypfstate(); $cpuusage= cpu_usage(); ?> <div id="show"> <c ...

Angular q.all: comparing immediate and delayed responses

Seeking advice on methodology: I currently utilize $q.all to handle multiple promises in a single return, processing all results as one request. For instance: $q.all([promise1(),promise2(),promise3(),promise(4),promise5()])..then(function(response){ ...} ...

What is the best way to determine the specific type of a value that is part of a union type?

Utilizing @azure/msal-react and @azure/msal-browser for implementing authentication in a React project with Typescript. The issue arises when TypeScript identifies event.payload as type EventPayload, but does not allow checking the exact type (e.g. Authen ...

Complete a checkbox entry form and showcase it within a "division" on the current page

Hello everyone, I need some help. I have a form that I want to send to a specific div on the same page. This is what I am aiming for. I have a floating div named "basket" in the top right corner of my page where I want the form data to be displayed after s ...

How do I customize the HOME page in JHipster to display unique content based on user roles?

I am currently developing a JHipster project where I need to display different home pages based on the role of the user logging in. Specifically, I am utilizing Angular 1.x for this project. For instance, I have roles such as ROLE_ADMIN and ROLE_USER, each ...

Automatic page switch upon dropdown selection

I'm not very proficient in JavaScript and I want to modify a form so that it automatically updates when a dropdown option is selected, without needing to click a separate "Go" button. How can I adjust the code below? It contains three different dropd ...

Exploring the filtering capabilities of Firebase using Vue

I am currently trying to enhance the search functionality in my firebase database to enable users to easily locate the product they are looking for. My current approach involves matching the search query, stored in this.searchText, with the product titles ...

I am unable to load any HTML files in my VueJS iframe, except for the index.html located in the public

Within the template of my vue component, I am utilizing the following code: <iframe width="1000vw" height="600vh" src="../../public/myHtmlFile.html"></iframe> Unfortunately, the file specified in the src attribut ...

What is the best way to include several IDs in a discord.js verification process?

I am attempting to create a basic script that verifies if the user's ID matches the one specified in the code. However, I'm struggling to understand how to achieve this. Any assistance from you all would be greatly appreciated. if(message.autho ...

Can you explain the purpose of the node_modules folder within AngularJS?

While exploring the AngularJS tutorial project, I came across the tutorial with a surprisingly hefty 60-megabyte node_modules directory. Does a simple clientside javascript project truly require such a large amount of unfamiliar data? I decided to delete ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...

Scraping data from a webpage using Node.js and the Document Object Model

I am attempting to extract information from a specific website using Node.js. Despite my best efforts, I have not made much progress in achieving this task. My goal is to retrieve a magnet URI link which is located within the following HTML structure: < ...

Switch between two distinct menus (Reactjs + Material UI)

Recently, I designed a robust menu system that includes a Switcher feature. The concept is straightforward - if the switch is turned off, display the 1st menu; and if it's on, show the second menu. However, there seems to be an issue. When the switch ...

Is there a way to change a weather api into local time using ReactJS/JavaScript?

In order to display time in a specific format like 12:00 or 20:00 and change the background with images, I need to convert it to local time. This is essential for achieving my desired output. The JSON data structure that I am working with looks as follow ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

Creating a React component with a column allowing multiple checkbox selections in NextUI table

Setting up multiple "checkbox" columns in a table using the NextUI table has been my current challenge. Each row should have selectable checkboxes, and I want these selections to be remembered when navigating between pages, running searches, or removing co ...

The interface 'children: string' does not share any properties with the type 'IntrinsicAttributes'.ts(2559)

When I export the component, the value from the input email does not appear as a VALUE property. How can I collect the text written in this exported component in my code? NOTE: I am working on developing a design system using STORYBOOK. export const Login ...