Determining the spatial location of an object in Three.js in relation to the camera for the purpose of creating a trail

In my scene, I have an object (a pen) that rotates around its axis in the render loop using the following code:

groupPen.rotation.y += speed;
groupPen.rotation.x += speed;

Additionally, I have a TrackballControls that allows the user to rotate the entire scene. Now, I want to determine the actual position of the pen (or its tip) and place small spheres to create a trail behind it.

This entails knowing where the camera is focused and positioning the trail spheres behind the pen tip while excluding them from the animation and TrackballControls.

I attempted the following:

groupSphereTrail.lookAt(camera.position);

However, this did not yield any results.

camera.add(groupSphereTrail);

When I tried this, the groupSphereTrail was positioned outside the view area, and adjusting its position.z did not make it visible.

Another approach I considered was using a raycaster to create a trail behind the pen. By sending a ray from the camera's center through the pen tip, I hoped to draw the trail. Yet, this method still did not provide me with the true position.

Another idea was to generate a 2D vector of the pen tip's current position and overlay an HTML element on top of the canvas:

var p = penPeak.position.clone();
var vector = p.project(camera);
vector.x = (vector.x + 1) / 2 * width;
vector.y = -(vector.y - 1) / 2 * height;

Unfortunately, this approach also failed to deliver the desired outcome.

Is there another effective solution for this issue?

To view the current progress, visit: (click on the pen cap to see the writing trail, which should remain in place even when rotating the camera).

Answer №1

If my understanding of the question is correct, you are looking to display the trail as if it were being drawn directly on the screen itself (screen space)?

yourTrailParticle.position.project(camera)
camera.add(yourTrailParticle)

That's the general idea, but it can get a bit complex with a PerspectiveCamera. One approach could be setting up a new THREE.Scene specifically for the trail, and then rendering it with an orthographic camera of fixed size.

The key is that .project() provides you with a normalized screen space coordinate based on a world space vector, and you need to ensure that it stays synchronized with the camera (given the perspective distortion). Using a separate scene might simplify this process.

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

Safeguard your contact information on the screen

On my classified website, I have concerns about the contact numbers being displayed as plain text in the product details page. This makes them visible to search engines. Is there a way to protect or display phone numbers as images to keep them hidden fro ...

The FlexDirection property in React Native is malfunctioning when set to 'row'

I'm having trouble getting these items to display in a row horizontally, and I can't figure out why. Any assistance would be greatly appreciated! const TextComponent = () => { const Menu = [ {'id':1, 'menuName':'F ...

When a user clicks on an image, I would like to dynamically resize it using a combination of PHP

Although I have a good understanding of CSS and HTML, my knowledge of Javascript is limited. I am looking to add an interactive element to my website where an image enlarges gradually when clicked and smoothly moves to the center of the screen in one con ...

Puppeteer: effective method for identifying and interacting with frequent popups in a loop

Seeking assistance in handling multiple popup windows simultaneously. Referencing the code snippet below: const newPagePromise = new Promise(res => browser.on('targetcreated', target => res(target.page()))); for(const dataWorkSheet ...

What steps should I take to ensure axios is returning the appropriate buffer type?

Upon initially posting this question, I was completely lost on where to even begin or how to appropriately title it. With the assistance of multiple comments, I enhanced the data provided and finally settled on the current question title - a big thank you ...

Buefy table in Vue with various row statuses

One interesting feature of Buefy tables is the ability to highlight rows with a specific color based on a variable in the row. :row-class="(row, index) => row.variable === x && 'is-info'"> In order to style the specific row class: <styl ...

(MUI Textfield) Error: Unable to access properties of undefined (specifically 'focus')

I have been working with the useRef hook in my Material Ui Textfield and have encountered the error Uncaught TypeError: Cannot read properties of undefined (reading 'focus'). I am unsure how to resolve this issue. Here is my current code snippet: ...

What causes TypeScript generics to infer varying types when an array member is enveloped?

I'm having trouble finding an answer to this potentially duplicate question, so please redirect me if it has already been addressed. My experience with generics in TypeScript has shown me that the inferred types can vary based on whether a generic is ...

JavaScript function for submitting form data using AJAX and performing validation

This is the code I have been working on: $(function () { $('.contact-form').submit(function (event) { $(this).find("input , textarea").each(function () { var input = $(this); if (input.val() == "") { ...

Looking for assistance in setting up an auto-suggest feature that displays retrieved or matched data from the database in a list format

I am currently facing an issue with the following problem: I have a form that includes a single search field with autosuggest functionality. I want to be able to type either a name or mobile number in this field. As I type, suggestions should appear base ...

elementToBeClickable is not supported by webdriverio

I am having some trouble with the 'waitForEnabled' function as it does not seem to behave like Webdriver's elementToBeClickable. Is there anyone who can provide some guidance on how to use this API effectively? ...

Wait for the completion of a Promise inside a for-loop in Javascript before returning the response

After completing a Promise within a for-loop, I am attempting to formulate a response. Although I have reviewed these questions, my scenario remains unaddressed. The methodGetOrders and methodGetLines are components of an external library that must be ut ...

The connected callback does not trigger when custom HTML elements are being created

Attempting to craft a custom HTML tag using JavaScript, I aimed to create the custom element with ES6 JavaScript syntax. The code devised for this task reads as follows: customElements.define('neo-element', NeoElement); function NeoElement (){ ...

Tinymce removes <html> tags from the output displayed in a textarea

I have created my own small CMS using Tinymce. When I insert plain text in pre tags, the code displays correctly on the website. However, when I update the editor, the HTML tags are removed. My Tinymce setup: <script type="text/javascript"> tinyMCE ...

Replace the ngOnDestroy method

Is there a way to complete an observable when the ngOnDestroy is triggered? I'd prefer not to create new child components when dealing with just one component instance. I attempted to override ngOnDestroy by modifying the function in the component&apo ...

When trying to show a Vue view, there was an issue with reading properties of null, specifically the 'style' property

I am experiencing an issue with a header that has an @click event in the body. Instead of displaying a Vue view upon clicking, I am encountering the following error: Cannot read properties of null (reading 'style') Upon researching on Stack Ove ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Tips for refreshing the page using NavLink from React-Router?

Is there a way to use NavLink to highlight buttons with an active link and still load the page like an anchor tag? ...

Tips for importing and exporting icons in a way that allows for dynamic importing using a string parameter

I am facing an issue with dynamically importing SVG icons in React Native. Initially, I tried using the following code snippet: const icon = require(`@src/assets/icons/${iconName}`) However, after realizing that this approach wouldn't work for me, I ...

Dynamic background color changes with each click or scroll

I have successfully created a function to Generate Background Colors, but the problem arises when I interact with the page by clicking or scrolling, causing the background colors to change repeatedly. HTML: <ion-button shape="round" color="clear" [ngS ...