Choosing an item using the mouse - Three.js

I have a question that I need help with. I'm trying to change the color of an object when it's selected with the mouse, but the code I wrote doesn't seem to be working correctly. Here's what I have so far:

    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize( window.innerWidth/2, window.innerHeight/2 );
        renderer.setClearColor( 0xcccccc, 1 ); 
        document.body.appendChild( renderer.domElement );
        scene.add(camera);

        var geometry = new THREE.Geometry();
        geometry.vertices.push(
            new THREE.Vector3( -5,  5, 0 ),
            new THREE.Vector3( -5, -5, 0 ),
            new THREE.Vector3(  5, -5, 0 )
        );
        var face = new THREE.Face3(0, 1, 2);
        geometry.faces.push(face);
        var material = new THREE.MeshBasicMaterial({color: 0x3300ff});
        var triangle = new THREE.Mesh(geometry, material);
        scene.add(triangle);

        camera.position.z = 10;

        document.addEventListener( 'mousedown', onDocumentMouseDown );

        function onDocumentMouseDown( event ) {    
            event.preventDefault();
            var mouse3D = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1,   
                                    -( event.clientY / window.innerHeight ) * 2 + 1,  
                                    0.5 );     
            var projector = new THREE.Projector();                                        
            var raycaster = projector.pickingRay( mouse3D.clone(), camera );
            var intersects = raycaster.intersectObjects( objects );

            if ( intersects.length > 0 ) {
                intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
            }
        }

        var render = function () {
            requestAnimationFrame( render );
            camera.lookAt( scene.position );
            renderer.render( scene, camera );
        };

        render();
    </script>

If anyone could provide assistance, I would greatly appreciate it.

Answer №1

Modified the code and included a link to JSFiddle

In the onDocumentMouseDown function, integrated:

var raycaster =  new THREE.Raycaster();                                        
raycaster.setFromCamera( mouse3D, camera );

instead of using:

var projector = new THREE.Projector();                                        
var raycaster = projector.pickingRay( mouse3D.clone(), camera );

Added a triangle mesh to the objects array and adjusted the renderer's size. I recommend utilizing the Console for debugging purposes. You should be able to identify and resolve these issues independently.

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

I'm curious about something I noticed in an HTML example within the text content section of elements. Can you help clarify this for me?

I recently came across a repository that was part of a bootcamp curriculum for learning full stack development. In one of the lessons on jQuery, students were tasked with building a calculator. However, I noticed some strange variables in the HTML where te ...

Is there a way to extract only the value from the most recent request?

While working with VueJS, I have a handler for changes in an input field that looks like this: inputHandler(url, params){ const p = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST&ap ...

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 ...

Enigmatic void appears above row upon removal of content from a single item

When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it. I have found that using flexbox could solve this issue, ...

Calculate the average value of the properties of a jQuery object

Consider the object below: rating { atmosphere: 85 cleanliness: 91 facilities: 91 staff: 85 security: 94 location: 78 valueForMoney: 85 } I'm looking to calculate the average of all these property values. Can y ...

How do you add dynamic content to modals in AngularJS and Angular Strap based on the button that was clicked?

Is there a way to make the buttons in the AngularJS + AngularStrap modal more dynamic? Currently, they display static content, but I would like them to show the content of the first column (first name) of the exact row where the button was clicked. What is ...

Vue Pinia ensures that reactive state is only updated once, preventing unnecessary updates

In my Vue application, the structure is as follows: App.vue -GroupWrapper --GroupListing -PeopleWrapper --PeopleListing -ConversationWrapper Within my user store that utilizes Pinia, I primarily call user.findChats() in the App.vue component. Code snippe ...

Can HTML text areas be designed to adjust their width automatically, as well as their height?

Among the numerous StackOverflow examples showcasing an auto-height Textarea, one noteworthy example can be found here: <textarea oninput="auto_grow(this)"></textarea> textarea { resize: none; overflow: hidden; min-heig ...

access the content of a div element by its class attribute

Within the div element, a value has been set and I am attempting to retrieve this value using its class. However, the code below does not return the desired value. What mistake am I making here? How can I resolve this issue? <div title="Find on Amazo ...

Is there a way to resolve the issue of my localStorage getting overridden on page refresh?

I am currently working on a simple React app and encountering an issue with the localStorage. Whenever I refresh the page, the todo list stored in the localStorage disappears. How can I ensure that the todos remain visible even after a refresh? Any sugges ...

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it ...

What is the best way to categorize a collection of objects within a string based on their distinct properties?

I am working with an array of hundreds of objects in JavaScript, each object follows this structure : object1 = { objectClass : Car, parentClass : Vehicle, name : BMW } object2 = { objectClass : Bicycle, parentClass : Vehicle, name : Giant } object3 = { ob ...

Differentiating between the simple and luxurious text editing features available in the TinyMce editor

I am currently utilizing the TinyMCE editor to enhance the appearance of a textarea field where users can input comments. My goal is to offer two options for users: one for plain text and the other for a rich text editing experience. When a user selects th ...

Looking to remove an item from an array using Redux?

Is there an issue with my reducers? Here is how they are set up: export default (itemsList = [], action) => { if (action.type === 'ADD_ITEM') { return [...itemsList, action.payload] } return itemList } The deleting reduce ...

How can you prevent a draggable element from surpassing the bottom of the screen?

I'm dealing with an element that I want to make draggable only along the Y-axis. It needs to be able to go past the top of the screen, but I need to restrict it from going past the bottom of the screen. I recently came across the containment feature i ...

Angular implementation of checkboxes to streamline data filtering

I am currently displaying FreeEvents using a checkbox and passing the value to the filter as filter:filterFreeEvent, which is working perfectly fine. However, I would like to avoid passing the value in the filter and instead use a change event of a checkb ...

Is it possible to create an <h1> heading that can be clicked like a button and actually do something when clicked?

I am currently designing a web page that includes <div class="cane-wrap"> <h1 class="mc">christmas tic tac toe</h1> </div> https://i.sstatic.net/R3Yps.png located at the top center of the webpage, with ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...