Selecting objects using a mouse pointer in Three.js

Is it possible to implement mouse picking on imported 3D models like a .obj file in Three.js? I've found plenty of tutorials for default objects, but I'm struggling to display a sphere at the exact position where the user clicks the model. Can anyone provide a tutorial or example source code to help me achieve this? I find tutorials to be the most effective way to learn. ;)

UPDATE: I've managed to get mouse picking to work on the model! However, I'm now trying to show a small dot at the location where the user clicks on the model. I've tried following a demo similar to this one: , but I can't seem to make it work. Any ideas on what I might be doing wrong? See the code below for reference.

// Your Three.js code goes here

Answer №1

Whether you're working with an imported model or a default object, the mouse picking code in Three.JS examples is universally compatible with any type of mesh.

Check out this link for more information.

var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
projector.unprojectVector( vector, camera );

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

var intersects = raycaster.intersectObject(mesh); 

Make sure to use the meshes created by the loader within the raycaster.intersectObject function. You can extract all meshes that make up an object using the following loading code.

var loader = new THREE.OBJLoader( manager );
loader.load( 'example.obj', function ( object ) {
    object.traverse( function ( child ) {
        if ( child instanceof THREE.Mesh ) {
            //This child element is essential for the raycaster.intersectObject() method
        }
    } );
    object.position.y = - 80;
    scene.add( object );
} );

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

How can I display every index from my JSON Fetched Files?

In the picture shown here, I have a series of Tables being displayed: https://i.sstatic.net/YUZD1.png The issue highlighted in red is that I want to show the Index of each JSON array as the Table number. Below is the code snippet: function getExternal( ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

Undefined boolean when passing to AngularJS directive

I developed a custom directive that allows for the addition of a gradient background color in AngularJS: .directive('colouredTile', function () { return { restrict: 'A', controller: 'ColouredTileController&apos ...

Struggling with transferring form input data to a different file using JavaScript, Node.js, React.js, and Next.js

I've been struggling with writing form input to a separate file in JavaScript. I created a demo repo to showcase the issue I'm facing. Check it out here: https://github.com/projectmikey/projectmikey-cant-write-to-api-dir-stackoverflow Locally, t ...

Divinely favored - pay attention for each and every sound

Currently, I am utilizing node with the blessed tty library downloaded from NPM. Within this library, there is a method called "key" that I am using in the following way: blessed.key(['q', 'z'], function(ch, key) { //do something ...

Tips on arranging jQuery deferred objects in order?

I am facing an issue where I need to delay every Ajax call until the previous function (hashcode.Sign()) has completed. Unfortunately, my current code does not wait for hashcode.Sign() to finish, causing problems as this function creates a new session that ...

How to remove checkbox border using HTML, JavaScript, and CSS

Is it possible to remove the square border from a checkbox in HTML? ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

The memory usage steadily increases when you refresh data using the anychart gantt chart

I have a basic anychart code to update a gantt chart every second: function initializeSchedule(){ anychart.onDocumentReady(function () { anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) { documen ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...

Utilize PHP SVG images to trigger internal JavaScript code through the <img> tag

Here is a php function that generates an SVG image. public function actionJsTest() { header('Content-Type: image/svg+xml'); $svg = ''; $svg .= '<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/ ...

Guide on dragging and dropping without losing the item, allowing for continuous drag and drop functionality

function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementB ...

Converting a JSON object into a format suitable for transmission through AJAX requests

I am attempting to transmit data in a JSobject via AJAX using jQuery. Below is the json object: var cookieData = { 'land' : document.URL, 'ref' : document.referrer }; The object is then stored in a cookie... throu ...

Step-by-step guide on redirecting to a different page following a successful POST API call using Jquery

I have the code below in my JavaScript file. $scope.addLookupAction = function () { $("#importForm").attr("action", 'xyz.com'); success:function(response) { $log.info("Redirecting to lookup home page"); ...

provide the key and id to a node.js module

Currently, I am utilizing the Express framework to establish a module for handling requests to a third-party API. This particular API necessitates an ID and key to be transmitted. Rather than embedding these credentials directly into the module, I prefer ...

The element 'stripe-pricing-table' is not a recognized property of the 'JSX.IntrinsicElements' type

I am currently trying to incorporate a pricing table using information from the Stripe documentation found at this link. However, during the process, I encountered an issue stating: "Property 'stripe-pricing-table' does not exist on type &ap ...

The Next Js 13 API route is failing to retrieve accurate data following a post request

I've been working on a project involving authentication using Django backend and Next.js frontend. For state management, I'm utilizing Redux Toolkit. However, I've encountered an issue with the Next.js API that communicates data to the backe ...

Angular website showing only app.component.html on the frontend

I'm currently working on developing the frontend for my API and I've encountered an issue while trying to create a new component. Despite my best efforts, including setting up an app-routing.module.ts file, my application only displays the conten ...

if statement not recognizing data returned from PHP function

I'm currently working with a function that is being used for an AJAX query: var formData = $(this).serialize(); //store form names and values in an array called 'formData' $.get('filtertest.php',formData,processData); //jQ ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...