Object placed at the mouse position is shifted from its original location

I am working with ThreeJS in conjunction with MindAR, attempting to position an object where I click on the screen using my mouse.

const mousePositionX = (e.clientX / window.innerWidth) * 2 - 1;
const mousePositionY = -(e.clientY / window.innerHeight) * 2 + 1;
const mouse = new THREE.Vector2(mousePositionX, mousePositionY);

const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);

const intersects = raycaster.intersectObjects(scene.children, true);
if (intersects.length === 0) return;

topping = obj1.clone();
topping.position.set(mouse.x, mouse.y, 0.25);

There are additional sections of code that involve adding this object to the anchor group (an AR term), etc.

The outcome is displayed below. In the two images provided, I am clicking at the very bottom of the pizza dough.

Viewing the object from a top-down perspective, it correctly positions the topping at the precise location of the mouse click: https://i.sstatic.net/pBsTj7vf.png

However, when viewed at an angle, the topping appears slightly offset: https://i.sstatic.net/f5ujVi86.png

Answer №1

It seems that the mouse coordinates are not matching the scene coordinates properly, especially when the camera is being rotated. As a result, this discrepancy leads to inaccuracies in translating to the 3D world. To address this issue, you can obtain the intersection point from the raycaster result by using intersects[0].point for precise 3D coordinates.

You can try implementing something similar to this code snippet:

const mousePositionX = (e.clientX / window.innerWidth) * 2 - 1;
const mousePositionY = -(e.clientY / window.innerHeight) * 2 + 1;
const mouse = new THREE.Vector2(mousePositionX, mousePositionY);

const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);

const intersects = raycaster.intersectObjects(scene.children, true);

if (intersects.length === 0) return;

const intersectionPoint = intersects[0].point;

const topping = obj1.clone();
topping.position.copy(intersectionPoint);

topping.position.z += 0.25;

scene.add(topping);

If you're still facing issues, it's possible that there might be some errors in other parts of your code. You may want to refer to this example for guidance:

<script type="importmap">
  {
"imports": {
  "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4c0dcc6d1d1f4849a8582829a84">[email protected]</a>/build/three.module.js",
  "three/addons/": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70041802151530405e4146465e40">[email protected]</a>/examples/jsm/"
}
  }
</script>

<script type="module">
import * as THREE from "three";
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// Rest of the provided example code...

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

struggling to send JSON data to PHP using AJAX

Here is the code snippet I am currently using. Javascript <script type="text/javascript"> var items = new Object(); items[0] = {'id':'0','value':'no','type':'img','filenam ...

Invoke the ngOnInit method in Angular 7 or any other method within the component itself

My current dilemma involves a component named user-table-list, which essentially represents a table with entries corresponding to various users. Within this setup, there exists another component called table-list, responsible for defining the structure a ...

A guide on utilizing webpack devServer proxy within a create react app

Currently, I am in the process of developing a new application with create-react-app and I am looking to incorporate some proxies into my code. In the past, I utilized webpack's devServer for this purpose. module.exports = { ... devServer: { ...

Setting up Apache's mod_proxy for handling ProxyPass and ProxyPassReverse to facilitate cross-domain ajax requests

I'm currently developing an HTML5-JavaScript mobile app using PhoneGap and need to interact with a REST service. The REST service is hosted at "http://localhost:8080/backend/mvc/" My development environment consists of a WAMP server (Apache2) at htt ...

Every time I try to use AgGrid selectors, they consistently come back with null results, even though the

I currently have an ag grid in my application: <app-my-component> <ag-grid-angular [gridOptions]="gridOptions" (gridReady)="setGridReady()"> </ag-grid-angular> </app-my-component> When running Karma- ...

Looking to cycle through arrays containing objects using Vue

Within my array list, each group contains different objects. My goal is to iterate through each group and verify if any object in a list meets a specific condition. Although I attempted to achieve this, my current code falls short of iterating through eve ...

What is the best approach for running a database query using the value selected from a form dropdown?

Currently, my application server is ColdFusion and I am using SQL Server for the database. Within a select form element on my webpage, users can choose from a list of vehicles such as Volvo S60, BMW M6, and VW Jetta. Once a user selects a vehicle, I need ...

What is the process for configuring the zoom control feature?

When utilizing react-google-maps, I am encountering issues with changing the zoom position as per the following code snippet: <GoogleMap defaultZoom={5} defaultCenter={{ lat: 22.845625996700075, lng: 78.9629 }} options={{ gestureHandling:'greedy ...

Steps for choosing all choices in a multi-select menu without changing the order

What is the best way to choose all the options from a multiselect box using Java Script? ...

New message being loaded by Ajax post-operation

Hey, I've written an ajax script for adding data to a database. The issue I'm facing is that when new data is added, the same message stays on the screen making it difficult to know if the new operation is completed. Is there any way to hide the ...

The Johnny-Five stepper initiates movement within a for-loop

I am new to using node.js and johnny-five. I want to move a stepper motor 5 times with 1000 steps each. Here is what I have tried: do 1000 Steps in cw ; console.log('ready); do 1000 steps; console.log('ready') ... It woul ...

Revamp the table layout for mobile with a unified markup structure

I want to customize the display of my bootstrap table for mobile view. Each row entry should be shown in a separate box or card, similar to the following examples: First: Mark Last : Otto Handle: @mdo Second card- First:Jacob Last:Thornton Handle:@fat Is ...

Ways to extract information from a dynamically generated table

I'm facing an issue with retrieving data from a dynamically generated table within my script... Here is the code snippet: $('#update_panel').html('Loading Date....'); $.ajax({ url: '/Home/GetCountries', type: & ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...

What is the best way to display a border around text in an HTML element when the mouse hovers over it?

I am currently developing a Browser Helper Object (BHO) for Internet Explorer that involves searching for specific words on a web page and encasing those words in an HTML tag for styling purposes. While I have code in place that allows me to change the st ...

The issue of Angular's ng-repeat view not refreshing after a search query remains unresolved

Having some trouble with updating a results array in AngularJS using a service call. After submitting a form and calling the service, I set up my callbacks with .then() on the promise object. However, the view only updates when I start deleting characters ...

How can you send an array from Django to JavaScript without using u''?

When viewing the data: 'some_array': ['text1','text2', 'text3'] Upon trying to pass it to a JS script in the template: <script type="text/javascript"> some_func({{ some_array }}); </script> Howeve ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...

What is the best way to retrieve the page slug within the layout file in Next.js, specifically when using the app folder structure?

In my latest project, I have implemented a nested layout using the new app folder. Within this layout, I have included a header that appears across all pages in the path www.mysite.com/some-slug. One issue I am facing is with the signup button located in t ...

efficiency of this algorithm

function checkSubset(array1, array2) { const set1 = new Set(array1); const set2 = new Set(array2); for (const element of set2) { if (!set1.has(element)) { return false; } } return true; } Can we consid ...