Ways to identify mouse clicks on three.js sprite

I am trying to implement a click event detection on a three.js sprite using the following code:

function bindEvents(state) {
  let intersected;
  function onDocumentMouseDown(event) {
    event.preventDefault();
    const mouseX = (event.clientX / window.innerWidth) * 2 - 1;
    const mouseY = - (event.clientY / window.innerHeight) * 2 + 1;

    const camera = state.threeD.elements.camera;
    const raycaster = state.threeD.raycaster;

    raycaster.setFromCamera(new THREE.Vector2(mouseX, mouseY), camera);

    var intersects = raycaster.intersectObjects(state.clickables?state.clickables:[]);
    if (intersects.length > 0) {
      if (intersected) intersected.material.map = intersected.currentMap;
      intersected = intersects[0].object;
      intersected.currentMap = intersected.material.map;
      intersected.material.map = selectCityTexture(128, '#cccccc', 'cccccc');
    }

  }

  document.addEventListener('mousedown', onDocumentMouseDown, false);
  document.addEventListener('touchstart', onDocumentMouseDown, false);
}

Despite almost working, there seems to be a slight offset in the mouse position. I suspect it may be due to a calculation error within the code. I would greatly appreciate any assistance in understanding and resolving this issue.

Answer №1

let xPosition = (event.clientX / window.innerWidth) * 2 - 1;
let yPosition = - (event.clientY / window.innerHeight) * 2 + 1;

These calculations have been updated to:

let xPosition = (event.clientX / canvas.width) * 2 - 1;
let yPosition = - (event.clientY / canvas.height) * 2 + 1;

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

Having trouble establishing a basic websocket connection in NodeJS

I am currently following a tutorial on WebSocket protocol development from this link: . Upon visiting localhost:1337/index.html, I encountered the following error: This localhost page cannot be found. No webpage was found for the web address: http://loc ...

Can a universal Save File As button be created for all web browsers?

Currently, I am in the process of developing a music player on the client side and I am seeking a method to save playlists that include mp3 data. Concerns with localStorage The restriction of a 5mb limit for localStorage makes it impractical for my needs. ...

Modifying the scope variable does not trigger an update in the AngularJS directive

Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this: <layout name="Default">My cool content</layout> into this output: <div class="layoutDefault">My ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

What steps are necessary to configure karma webdriver launcher to utilize my selenium server or grid?

Could someone assist in identifying what is causing the Karma javascript test runner to have issues connecting to and utilizing my selenium grid/server? I currently have a functioning selenium grid setup that I utilize with python selenium bindings for co ...

Make Fomantic-UI (Angular-JS) sidebar scroll independently

Is there a way to make a sidebar scroll independently of the content it pushes? Currently, my page is structured like this: -------------------------- |[button] Header | -------------------------- |S | Main content | |i | ...

Discovering which chip has wrapped to the next line in Material UI Autocomplete can be found by closely inspect

Currently, I am working with a Material UI autocomplete feature that functions as follows: My goal is to determine when the fourth chip wraps to the next line within the autocomplete so that I can proceed with additional calculations. Is there a method in ...

In JavaScript, private variables are not included in the JSON.stringify output

Imagine creating a class called Rectangle with private fields like width and height, initializing them in the constructor. However, when calling JSON.stringify on an instance of this class, it returns an empty object without including the private members. ...

Creating models or bulk creating promises in a seed file

When working with a promise chain to add data in JavaScript, I usually start by using Node.js or another method and it works fine (with some variations). However, when attempting to implement this promise chain in a sequelize seed file with the sequelize- ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Which specific page initiates the post request?

Seeking help with my post request that originates from a specific page on my website: reqdata = 'text=' + mytext; $.ajax({ type: "POST", url: "/request.php", data: reqdata, cache: false, success: function(html) { alert(html) } ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Tips for assigning custom values using CSS and jQuery for a standalone look

I am facing a challenge with my HTML markup: <div> <figure></figure> <figure></figure> <figure></figure> </div> Alongside some CSS styling: div { position: relative; } figure { position: absolu ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

Sliding Image Menu using jQuery

I am struggling with creating a menu using jquery mouseenter / mouseout effects. My goal is to have a small icon displayed that expands to the left and reveals the menu link when a user hovers over it. The issue I am facing is that the effect only works w ...

Refreshing pane content within Kendo UI Splitview

I am utilizing the Kendo UI splitview. In my setup, I have configured one pane on the left for navigation and another pane on the right for content display. The left pane contains 4 navigation links structured as follows: <div data-role="pane" id="si ...

Pass the identification of a particular card to the following route in order to retrieve data using that specific id in nextjs

[]Hello! I am currently working on fetching data from an API and using the map function to display the retrieved data. My goal is to extract more details about a specific piece of data by taking its ID and passing it to another page. The issue arises in my ...