Exploring Sprite Range with Raycasting in Three.js

I am working on a 3D scene using three.js and adding sprites, but I want to accurately determine the distance between the camera and a sprite when I click on the screen. To achieve this, I am utilizing a Raycaster.

However, when clicking on the sprite, the "distance" property of the intersection object is consistently displaying what seems to be an incorrect value (such as 0.3), leading me to question whether I am interpreting the result correctly. My expectation was that the "distance" value of the intersection object would represent the actual distance from the camera to the sprite (which in my scenario should be around 5).

Here is a condensed snippet of my code:


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, window.innerHeight);
document.body.appendChild(renderer.domElement);

var sprite = new THREE.Sprite(new THREE.SpriteMaterial({color: 0x00ff00}));
scene.add(sprite);

camera.position.z = 5;

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

render();

window.addEventListener('mousedown', function (e) {
    if (e.target == renderer.domElement) {
        var vector = new THREE.Vector3((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1, 0.5);
        var projector = new THREE.Projector();

        projector.unprojectVector(vector, camera);

        var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

        var intersects = raycaster.intersectObjects([sprite]);
        console.log(intersects[0]);
    }
}, false);

For a live demonstration, you can access it here: http://jsfiddle.net/pWr57/

Given the above, can anyone advise me on how to obtain the accurate distance from the camera to a sprite?

Version used: three.js r66

Answer №1

Instead of that, try this

displayDistance( raycaster.ray.origin.distanceTo( intersects[0].point ) );

Suggestion: Take a look at the code in Raycaster.js to understand its functionality. It currently calculates the perpendicular distance from the sprite center to the ray.

For this scenario, I recommend modifying it to calculate the distance from the camera instead.

Version three.js r.66

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

Maintain consistent size of object on screen regardless of how far it is from the camera

I am facing a challenge in Three.js where I have a rectangle that is moving away from the camera. I need to calculate a 3D x and y scale for the rectangle so that it maintains its size on the screen in pixels, regardless of how far it moves away from the c ...

Leveraging React Native's Async Storage to store and retrieve values consistently within the Render method

Is there a way to set and get a value in the render method with just one line of code, by using a variable between tags? I attempted this approach but encountered an error message stating "Can't find variable: storage_key". import React, { Component } ...

Guide on making an NPM package with a web worker integration

Currently, I am in the process of developing an npm package that incorporates a web worker with type module. The issue arises when I try to link this package to a React application for testing purposes since the application cannot locate the worker.js file ...

Unable to insert <form> element into the content of the popover

I am attempting to display a popover with content fetched from an API using AJAX. The content includes various HTML tags like <form> with a <textarea> and a <button>, <br/> tags, <a> links, and <time> elements. The issu ...

Error in Internet Explorer when attempting to close a Fancybox iframe that plays a YouTube video

Even the FancyApps page itself contains the error mentioned below. If you visit using Internet Explorer 9, for example, follow these steps: Go to Internet Options > Advanced > Disable script debugging (Internet Explorer). Then click on the YouTube ( ...

retrieve data from firestore and pass it as a parameter to a function

After successfully retrieving a field from Firestore and logging the correct information, I am now trying to set the name of my code as a reusable function. Below is the original code: db.collection('users').doc('' + sender_id).get(). ...

Encoding a two-dimensional array into JSON format

In my PHP script, I am querying a database and formatting the results as JSON: $query = mysql_query($sql); $rows = mysql_num_rows($query); $data['course_num']=$rows; $data['course_data'] = array(); while ($fetch = mysql_fetch_assoc($q ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...

Tips for setting a unique JWT secret in next-auth for production to prevent potential issues

Is there a way to properly set a JWT secret in NextAuth.js v4 to prevent errors in production? I have followed the guidelines outlined in the documentation, but I am still encountering this warning message without any further explanation: [next-auth][warn] ...

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...

Js: Automatically populating data into various input fields

I've encountered an issue with form input value injection using a <script> and POST requests. When I attempt to create another form with the same input field (same name and id), the value injection doesn't work, and troubleshooting has bee ...

Insufficient module names remaining in NPM

Starting to release modules on NPM has been on my mind, but I can't help but worry about the limited availability of sensible module names in the public domain. Is there a way to create a public NPM module that organizes all my module names within a ...

Creating a unique function to map an array in VueJS specifically designed for table manipulation

I am currently working on displaying and sorting data in a bootstrap table within VueJS. My goal is to change the date format within an array retrieved from an API endpoint. The original date format is in "January 21, 2010" and I need it to be in "MM/DD/Y ...

Breaking apart paragraphs in a text using JavaScript

Hello, I am working on a code that is supposed to extract paragraphs from text entered into a textarea and create an array containing each paragraph. For example, it should turn text like this: Hello, that's the first paragraph Hello, that's th ...

Tips for setting environmental variables to match ID values in html documents

In my API reference call, I have stored the key in a separate file and protected it using .gitignore since I am using GitHub. However, I am facing an issue on how to transfer that key from my JavaScript file into the HTML data-key attribute using a variab ...

Sending form data with file upload using MVC3

In my Create view, I have text inputs and an input type="file" for uploading an image. I am implementing jquery.Upload (http://lagoscript.org/jquery/upload) to post the image instantly and provide a preview before the user clicks Save. Issue: Since the fo ...

Creating a tool that produces numerous dynamic identifiers following a specific format

I am working on a function to create multiple dynamic IDs with a specific pattern. How can I achieve this? followup: Vue.js: How to generate multiple dynamic IDs with a defined pattern Details: I am developing an interactive school test application. Whe ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

How come the chosen item is not showing up in the bootstrap dropdown on WordPress?

I'm having trouble displaying the selected item in a bootstrap dropdown menu on WordPress. You can check out my site at . Ideally, it should function similar to this example: http://www.bootply.com/62811 https://i.sstatic.net/5d5FH.png Here is my men ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...