Utilizing Three.js to create a prominent point where the camera direction intersects with a spherical object

I am attempting to create a visible point on a sphere using three.js. This point should be where the line extending from the camera intersects the sphere.

The idea came from a helpful thread on Stack Overflow.

You can view my progress on this link

In the code provided, I have hidden the drawPointIntersection() function which is called after the render() function. This is where I handle the logic for drawing the point.

Below is the relevant section of code :

function drawPointIntersection() {

  // Direction of camera
  var direction = new THREE.Vector3(0, 0, -1);
  var startPoint = camera.position.clone();
  var ray = new THREE.Raycaster(startPoint, direction);  

  // Get point on sphere where camera direction intersects
  var rayIntersects = ray.intersectObject(scene, true);

  // Calculate distance between camera and point of intersection
  console.log(rayIntersects[0]);

  // Create point on sphere for camera direction
  var dotGeometry = new THREE.Geometry();

  // Trying to find correct syntax with coordinates of intersection point

  //dotGeometry.vertices.push(new THREE.Vector3(0, 0, 0));
  dotGeometry.vertices.push(new THREE.Vector3(rayIntersects[1]);
  //dotGeometry.vertices.push(new THREE.Vector3(rayIntersects.point.x, rayIntersects.point.y, rayIntersects.point.z);

  var dotMaterial = new THREE.PointsMaterial({size: 10, sizeAttenuation: false});
  var dot = new THREE.Points(dotGeometry, dotMaterial);
  scene.add(dot);
}

I have experimented with different syntax options to retrieve the coordinates of the point returned by ray.intersectObject(scene, true) but none have succeeded :

   dotGeometry.vertices.push(new THREE.Vector3(0, 0, 0));

   dotGeometry.vertices.push(new THREE.Vector3(rayIntersects[1]);

   dotGeometry.vertices.push(new THREE.Vector3(rayIntersects.point.x, rayIntersects.point.y, rayIntersects.point.z);

Note that the camera is moving around the sphere.

I am unsure why it isn't working, and would appreciate any guidance on how to obtain these coordinates to draw the point on the sphere using the THREE.Points method in three.js R75.

Thank you in advance

Answer №1

Every frame alters the camera's position, affecting the direction vector. To correct this issue, consider the following:

// Define initial camera position
var startPoint = camera.position.clone();

// Adjust camera direction
var direction = sphere.position.clone().sub(startPoint).normalize();

Focus on the intersection with the target object (sphere) exclusively:

var intersections = ray.intersectObject(sphere, true);

[ https://jsfiddle.net/7bp1e5xh/ ]

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

The issue of the Angular 4 double click event not functioning properly on mobile devices

I have implemented a double click functionality in my code, which is working perfectly in desktop view. However, I am facing an issue when switching to mobile or tablet view as the double tap feature does not work. Below is a snippet of my code: HTML: & ...

Ways to display notifications when the user is not actively browsing the website?

How can websites display notifications even when the user is not actively on the site? Take Facebook messenger, for instance. Even with the page closed, notifications still pop up. The same goes for Twitter, which also sends push notifications. I ...

Show only the items in bootstrap-vue b-table when a filter is actively applied

How can I set my bootstrap-vue b-table to only show items when a filter is applied by the user (i.e., entered a value into the input)? For example, if "filteredItems" doesn't exist, then display nothing? This is primarily to prevent rendering all rows ...

Tips for fetching integer numbers in a string in JavaScript in sequential order starting from the left side

Within an input element, users are required to input the price of a product. <input size=10 type="text" id="prd_price" title="prd_price" name="prd_price"> Users have the ability to enter Currency Symbols along with other characters, and we cannot ...

Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS fun ...

Continue running the remaining part of the function once the asynchronous function has completed its execution

To obtain the last 4 digits of a payment using Stripe, I need to execute an async function that contains another async function. Once these functions are resolved, I aim to update the database with the last four digits. It is crucial to ensure that the dat ...

Can date ranges be utilized as separate date items on the time scale in D3.js?

I have a chart that resembles the one shown below, however, there is a crucial component missing. Currently, my time scale follows the standard format as depicted in the first picture. I am looking to convert it to the time scale seen in the second picture ...

ReactJS is throwing an error stating that the component is undefined

Experimenting with ReactJS, I've set up a hierarchy of three nested components: UserProfile.jsx import React from 'react'; const UserProfile = React.createClass({ getInitialState: function() { return { username: "zuck" }; ...

jQuery functionality restricted to desktop devices

I am attempting to disable a jQuery function specifically for mobile devices. I found some instructions that seem helpful on this page. Unfortunately, following the instructions did not work for me. Here is the code snippet I have: var isMobile = /Androi ...

Mobile issue: unable to scroll to the top of the page

Despite my efforts in searching and attempting various solutions from SO, I have still been unsuccessful. I have explored options like the iscroll library and setting timeouts, but to no avail. My objective is to enable scrolling to the top of the window/ ...

Is there a way to verify if the current event marks the conclusion of the events transmitted to a webhook?

Currently, I am in the process of coding a Google Apps Script web app that will react to events from the Telegram API using a chat bot. The first step was setting up a webhook to collect these events through the Google webhook. Since logger.log is unavaila ...

I'm struggling to retrieve $wpdb data after using a PHP function to load my posts with AJAX

Hey there! I'm trying to create a cool feature where users can view post archives grouped by year. When they click on a specific year, all the posts from that year should be displayed. I've set up an AJAX call to my functions.php file, which con ...

Duplicate information in simultaneous jQuery ajax requests

While retrieving data from a table of links on a webpage, I initiate multiple ajax requests as I iterate through the table, increment a counter, and then call checkFinished() to see if all requests have been completed. Interestingly, even though the URLs ...

The challenge of default Vuetify styles within a Nuxt environment

Here is my code snippet: <div class="cd-page__details-wrapper"> <v-text-field label="Outlined" placeholder="Outlined" outlined ></v-text-field> </div> Unfortunately, something unexpecte ...

Executing JavaScript code within an AJAX request

Having a problem with an AJAX function that I need help solving: PAGE A represents the main page. PAGE X represents the content loaded via AJAX. RES A represents the results from PAGE A. RES B represents the new results loaded via AJAX. PAGE A initially ...

What is the best way to retrieve the src value upon clicking on an image in a JavaScript function with multiple images displayed on

I have 3 images on my website. Each time I click on an image, I want to retrieve the source value. I attempted the code below, but it doesn't seem to work with multiple images. <div class="test"> <a href="#" class="part-one" ...

Developing an easily optimized library using rollup to remove unnecessary code branches

I'm currently in the process of developing a component library using rollup and Vue with the goal of making it tree shakable for others who import it. The configuration setup is outlined below: Here's a snippet from package.json { "name": "re ...

Learn how to utilize the Page props in the getServerSideProps method with Next.js

I have passed some properties to the _app page. <PageWrapper> <Component someProps={someProps} /> <GlobalCSS /> </PageWrapper> Can these props be accessed in the getServerSideProps method on each individual Page? export const g ...

JavaScript's Extended Array feature is not functioning as anticipated, and no error message is being displayed

Hello, I am currently delving into JavaScript for a project I'm working on and have encountered a question regarding the following snippet of code. function randomArr(){}; randomArr.prototype = new Array(); randomArr.prototype.getRandomValue = funct ...

React component causing function to fire twice on click

Summary: My toggle function is triggering twice upon clicking the button. Within a React component (using Next.js), I am utilizing the useEffect hook to target the :root <html> element in order to toggle a class. The script is as follows: useEffect( ...