Selecting items using raycasting

Currently attempting to select objects when clicked, using the common code found in various examples:

function onMouseDown(evt) {

    evt.preventDefault();

    canvasAbsoluteHeight = $('canvas').height();
    canvasAbsoluteWidth = $('canvas').width();

    mouseDown = true;
    mouseX = evt.offsetX == undefined ? evt.layerX : evt.offsetX;
    mouseY = evt.offsetY == undefined ? evt.layerY : evt.offsetY;

    var mouse = new THREE.Vector3();
    mouse.x = ( evt.clientX / canvasAbsoluteWidth ) * 2 - 1;
    mouse.y = 1 - ( evt.clientY / canvasAbsoluteHeight ) * 2;
    mouse.z = 0;

    ray = new THREE.Raycaster( mouse, camera );

    var intersects = ray.intersectObjects( objects);
    console.log('intersects', intersects);
    if ( intersects.length > 0 ) {


        console.log('intersects', intersects);
    }

} 

objects is an array of THREE.Object3D that should be selectable.

It seems like there may be a connection with the camera. My camera is under a THREE.Object3D parent for easier manipulation, and the parent object is not positioned at the origin.

Another issue could be that the canvas is not full screen, which could affect the mouse position (it is within a div offset from the page edges).

Answer №1

Take a look at this interactive example. It includes a Picker class that can be utilized. Step one involves initializing this class with the camera and a specific DOM element.

Picker.init(camera, domelement)

Next, you need to attach a mesh to the Picker.

Picker.attach(mesh)

Finally, define the actions you want to occur after a mouse down or mouse up event using the Picker methods.

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

Issue: The module '[object Object]' could not be located

const express = require('express'); const app = express(); const jade = require('jade'); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').liste ...

The TypeScript compiler is generating node_modules and type declaration files in opposition to the guidelines outlined in the tsconfig.json file

For the past week, I've been trying to troubleshoot this issue and it has me completely puzzled. What's even more puzzling is that this app was compiling perfectly fine for months until this problem occurred seemingly out of nowhere without any c ...

What could be causing the redirection issue in a next.js application?

I recently started working with Next.js and have developed an application using it. On the homepage, I have a timer set for 10 seconds. When the timer hits 0, I want to redirect the user to a feedback page in my "pages" folder. Below is the code I am usin ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

What steps should I take to make sure the vuex store is included in my build process?

I am currently working on a Vue application using vue cli 3. I found a guide here that explains how to build the app with vue-cli-service build --target wc --name my-element [entry] In order to test the output, I have created an index.html file: <!D ...

Vue.js: Issue with updating list in parent component when using child component

I'm encountering an issue when utilizing a child component, the list fails to update based on a prop that is passed into it. When there are changes in the comments array data, the list does not reflect those updates if it uses the child component < ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

The function Firebase.database() is unavailable in the Sails Service

I have developed a service named Firebase.js, and I am attempting to utilize it from my Controllers by using Firebase.database. However, I am encountering an error stating that Firebase.database() is not a function services/Firebase.js var admin = requir ...

What is the best way to smoothly transition in an image that is dynamically set using Angular?

I am using Angular to set a background image for my page, but the current loading behavior is not visually appealing as the image loads from top to bottom. I would like to implement a fade-in effect or load the image from a blurry view to enhance the user ...

Syntax highlighting in custom blocks with VueJS

Vue single file components allow for the creation of custom blocks (besides the commonly used script, template, and style). For more information, you can refer to the official documentation here: . However, I am struggling to enable syntax highlighting w ...

Having trouble exporting a static HTML file using Next.js

https://i.stack.imgur.com/xQj7q.pngI'm a beginner in the world of React. Recently, I completed a project where I utilized "next build && next export" in my package.json file for static HTML export. By running the npm run build command, an out folder w ...

Adjusting the height of a textarea with javascript

I am trying to reset the contents and height of an auto resizing textarea element. My attempts so far include: document.getElementById('textarea').value = ''; As well as: document.getElementById('textarea').attribute(&apos ...

How can I dynamically assign a className in a React component based on the current state when importing styles?

I've been utilizing the style-loader to insert CSS modularly into my components ({style.exampleClassName}). My goal is to showcase a loader for a specific duration before displaying an image (at least 16 of these components in a grid layout). This i ...

Choose the data attributes you want to include and attach them to input elements using plain JavaScript

Creating a User Information form with a select element containing four options, each with data attributes. Under the select are input types to populate the data attributes when selected. Looking for help in achieving this using plain JS and onchange event. ...

Is there a way to implement absolute imports in both Storybook and Next.js?

Within my .storybook/main.js file, I've included the following webpack configuration: webpackFinal: async (config) => { config.resolve.modules = [ ...(config.resolve.modules || []), path.resolve(__dirname), ]; return ...

Why does the Formik form only validate after the second button click in this React Hooks, TypeScript, Formik, NextJS setup?

Looking for fresh perspectives on my code. The issue lies in the fact that it takes two submission attempts to validate the data inputted into a form successfully. It appears that the post request to Airtable happens before the validation schema, resulting ...

A Study on Particle Systems using THREE.js

While working on my particle System in THREE.js with SPARK.js, I have completed the necessary code for the system. However, I am facing an issue where nothing related to the Particle System is being displayed on the screen. Currently, I am trying to creat ...