Clicking the mouse within three.js

I'm facing an issue with my webpage that features a three.js (webgl) graphic created using a .dae file imported from Blender. My goal is to draw a square or mark wherever the mouse is clicked, but for some reason, the square appears in a different location than expected. I've researched various blogs looking for a solution, but so far, I haven't been able to pinpoint what mistake I might be making. Here is the code snippet:

<script src="three.js"></script>
        <script src="ColladaLoader.js"></script>
        <script src="TrackballControls.js"></script>
        <script>
            var dae;
            var camera;
            var renderer; 
            var loader = new THREE.ColladaLoader();             
            loader.options.convertUpAxis = true;
            loader.load( './dataFile.dae', function ( collada ) {
                dae = collada.scene;
                dae.traverse( function ( child ) {
                    if ( child instanceof THREE.SkinnedMesh ) {
                        var animation = new THREE.Animation( child, child.geometry.animation );
                        animation.play();
                    }
                } );

                dae.scale.x = dae.scale.y = dae.scale.z = 1;
                dae.updateMatrix();

                init();
                animate();

            } );

            function init() {
                container = document.getElementById( 'canvas' );
                document.body.appendChild( container );

                camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 5, 1000 );
                camera.position.set( 2, 7, 3 );
                controls = new THREE.TrackballControls( camera );
                controls.rotateSpeed = 1.0;
                controls.zoomSpeed = 1.0;
                controls.panSpeed = 0.8;
                controls.noZoom = false;
                controls.noPan = false;
                controls.staticMoving = false;
                controls.dynamicDampingFactor = 0.3;
                controls.addEventListener( 'change', render );

                scene = new THREE.Scene();
                // Add the COLLADA
                scene.add( dae );

                // Lights
                scene.add( new THREE.AmbientLight( 0xcccccc ) );
                light = new THREE.PointLight(0x000000);
                light.position.set(-100, 100, 100);
                scene.add(light);

                // Renderer
                renderer = new THREE.WebGLRenderer();
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( window.innerWidth, window.innerHeight );
                container.appendChild( renderer.domElement );

                // Miscellaneous
                document.addEventListener('click', onDocumentMouseClick);
                render();

            }

            function onDocumentMouseClick(event) {
                //event.preventDefault();
                var mouses = { x : 0, y : 0 };
                mouses.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / window.innerWidth ) * 2 - 1;
                mouses.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / window.innerHeight ) * 2 + 1;

                // Particle
                var dotGeometry = new THREE.Geometry();
                dotGeometry.vertices.push(new THREE.Vector2( mouses.x, .5, mouses.y));
                var dotMaterial = new THREE.PointCloudMaterial( { color: 0x000000, size: 8, sizeAttenuation: false } );
                var dot = new THREE.PointCloud( dotGeometry, dotMaterial );
                scene.add( dot );

                render();

            }
        </script>

Answer №1

I finally identified the root cause of the problem. It turns out that the camera's movement and zoom features were causing inaccuracies in registering click positions.

By turning off panning and zoom functionalities, all issues were resolved seamlessly.

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

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

Break down objects into arrays of objects in JavaScript

Hello, I'm struggling with transforming this object into an array of objects. The 'number' and 'reason' fields are currently stored as strings separated by commas. I need to split them into their own separate objects. The example ...

Tips for accessing the values of fields in React Material UI components

When I console log the object, it shows: { "week":undefined, "name":undefined, "code":undefined } Additionally, is it appropriate to wrap all Material UI components in a form tag and treat the entire code as a form? Here is ...

`Failure to prompt an error following an unsuccessful post request in a node.js application using axios and express`

I'm currently facing an issue while trying to implement password change validation. The problem lies in not receiving the errorMessage from the server in case of an error. Although I've successfully managed to update the password and send back a ...

Issues have been reported with the functionality of the ng-click function in Angular JS

Having just started using AngularJs, I am facing an issue where the function is not being called when I click the button that I append. HTML </tbody> <tr> <td><input type="text" class="form-control" ng-model="contact.name ...

Choosing an option from a dropdown menu using WebDriverJs

I am struggling to select a value from a dropdown box using WebDriverJS. Despite searching through the user guide, I have not been able to find a solution. https://code.google.com/p/selenium/wiki/WebDriverJs I even attempted to use methods documented f ...

Utilizing D3.js to selectively apply the nest.key() function to certain elements within an array

I have a CSV file containing hierarchical tree data as shown below: industry,level1,level2,level3,name Ecommerce,Web,,,Rakuten Ecommerce,Crowdsourcing,,,Lancers Social,Photo sharing,Deco apps,,Snapeee Social,Photo sharing,Deco apps,Collage apps,DecoAlbum ...

jQuery includes inArray as the final element in an array or object

There's a strange issue I've noticed where, in some cases, when jQuery is imported, it appends the inArray function as the last element of a defined object or array. This can cause problems with for ... in loops since it counts this unexpected fu ...

Is it possible to obtain the parameters using an empty object with the getStaticPaths function?

Within the getStaticPaths function, a path is returned with params postId:1. If additional params like postId: 2 or postId: 3 are included, they will also be statically generated. Is my understanding correct? Is there a way to avoid loading any post based ...

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...

What is the best way to utilize JQuery AJAX to send XML data for a delete request?

I am having trouble sending XML type data to the backend using jQuery and AJAX as a DELETE request. When I do this, I receive an empty array from the backend's request body. How can I properly send the ID? Below is the code I am using: function delet ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...

Does Three.js come with a default function for generating heightmaps?

Currently, I am engrossed in developing a JavaScript game using Three.js. My interest lies in enhancing the realism of the walls by incorporating a height map (refer to the provided image). View this snapshot of the game design featuring a 2D wall. All th ...

Utilize information stored in a database to automatically navigate to a different webpage

I am currently working with PHP, HTML, and a mySQL database. Here are my current project requirements: Retreive specific data from the database and output it. Compare this data with predetermined values. If the data falls outside of the specified range, ...

Refactor Print Preview Graph Display Issue within Nested Vue Component

I seem to be having trouble accessing this function properly due to an error. I am unsure of how to troubleshoot this issue and determine the correct solution. Any guidance would be greatly appreciated. The component PerformanceDonut.vue is located within ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

How do I retrieve child nodes' properties in JavaScript?

I am currently working on a link extractor using CasperJS, and the core function looks something like this: function extractLinks() { return Array.prototype.map.call(document.querySelectorAll('a'), function(e){ return { ...

How can I create a script in Discord.js that automatically sends users their information upon joining the server?

I'm currently working on developing a code that automatically sends the user's avatar, username, ID, account creation date, server join date, and status when they join The structure of the code looks something like this: module.exports = (Discor ...

Why won't my redux application store the results of an asynchronous API request using redux-thunk's caching mechanism?

I am new to using Redux in my project. Currently, I am developing an application that displays a list of soccer leagues in each country. The process involves fetching a list of countries first, then using the country names to fetch the soccer leagues. Not ...

Utilizing jQuery and DOM to interact with form elements

Below is the form content <form method="post"> <input type="hidden" name="resulttype" value="Create"> <table> <tr> <td>Full Name</td> <td><input ...