Tips for aligning meshes to the left and ensuring responsiveness in three.js

Currently working on a website using three.js, I'm facing an issue where I can't seem to align and make the mesh responsive simultaneously. My current approach to alignment is:

cube.position.x = -20

However, when I try resizing the window, the mesh doesn't adjust accordingly. How can I achieve responsiveness while also aligning it to the left?

Here's a snippet of my code:

const geometry = new THREE.BoxGeometry(29, 20, 3)
const material = new THREE.MeshBasicMaterial({ map: cubetexture });
const cube = new THREE.Mesh(geometry, material);
cube.position.x = -20;
scene.add(cube);

var clock = new THREE.Clock();

function animate() {
  requestAnimationFrame(animate);
  const time = clock.getElapsedTime();

  cube.position.y = Math.cos(time) * 2;
  cube.rotateY(Math.cos(time) * 0.002);
  renderer.render(scene, camera);
}

animate();

Thank you in advance for your assistance :)

Answer №1

Introduction

In this guide, I will explain how to accurately align 3D objects in your scene with a perspective camera. While this may seem challenging when working alongside other objects in the same scene, it is important to consider whether absolute alignment of 3D objects is necessary. For instance, for text or flat images, utilizing HTML with CSS can be a simpler and more manageable approach.

An alternative method, not discussed here, involves rendering items using an orthographic camera. This setup is straightforward due to the simplicity of orthographic math, and you can find numerous examples (1, 2) online for reference. Using an orthographic camera might be the ideal solution for your needs.

My personal project required creating a 3D visor for a game I am developing. I needed the player to have the ability to remove the visor while ensuring dynamic alignment with screen resolution and the flexibility to align objects to any edge of the screen, which I will discuss further.

Key Assumptions

This tutorial assumes that your objects will not move farther away from the camera spontaneously (if they do, they will move towards the center of the canvas). Achieving precise alignment requires complex calculations based on the geometry of a cone, which is beyond the scope of this discussion. Instead, I will provide constants that have proven effective in my workflow.

Step 1: Determine Ratios and Constants

Upon examining the screenshots below, under 1:1 resolution, the spaceship's dashboard appears at the bottom of the screen, while the windshield nearly reaches the top edge. This alignment remains consistent even at a widescreen 16:9 resolution. However, the cockpit's side view becomes less visible at a 1:1 ratio compared to 16:9.

This observation indicates that resolution changes primarily impact the x-axis (left-to-right) while leaving the y-axis (up/down) unaffected by resolution adjustments. In other words, the aspect ratio predominantly affects the x-axis in this scenario.

1:1 resolution:

https://i.sstatic.net/s0O1l.png

Widescreen resolution:

https://i.sstatic.net/1z2Dc.png

Step 2: Define the Center Point

To simplify alignment processes, establish a clear central point at 0, connecting your 3D objects directly to the camera. Assuming your object's origin is centered, this ensures automatic centering. If the object's origin deviates from the center, leverage a bounding box to enforce centering.

Note: If attaching objects to the camera is not ideal, consider attaching only during resizing operations and detaching afterwards. Since attachment does not alter world position, this workaround effectively maintains alignment.

Step 3: Establish Forward Axis

In 3D alignment, positioning objects in front of the viewer at a specified distance is crucial. For example, when designing a visor, place the objects approximately 5 centimeters from the player's face. To streamline the process, ensure that Blender models maintain a precisely measured longest edge of 1 meter, without variations like "at least" or "at most."

Step 4: Implementation Code

The following code assumes a standard unit length where 1 unit equates to 1 meter. This simplifies computations and maintains consistency, especially when referencing dimensions in tools like Blender (focusing on actual dimensions rather than scale).

I will present demonstrations showcasing center alignment, right alignment, and bottom-right alignment. These examples should provide sufficient guidance for extrapolating additional alignment scenarios by adjusting simple parameters such as changing the sign from - to + for top alignment instead of bottom alignment.

[Code snippets and implementation details provided]

Achieved real-world results are showcased below, featuring aligned 3D representations including a curved bar and bottom-right text elements.

p

https://i.sstatic.net/oLuTg.gif

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

Setting a Javascript value to a Controller variable within an ASP.NET MVC View

I am trying to set the javascript variable contentArea to match content.Contents in my controller. How can this be accomplished? <script language="javascript" type="text/javascript"> $("#btnTest").click(function () { var content ...

Error with review score in material-ui for react.js

There is an issue with my code where the ratings from different sets are not behaving independently. When a rating in one set is clicked, only the first set of ratings changes, suggesting that there is a connection between all the sets. https://i.sstatic. ...

What is the best way to pass a mask without using a plug-in when dealing with an input value in Vue.js?

As someone who has previously implemented the function using pure JavaScript, I am now faced with the challenge of incorporating it into vue.js and determining which lifecycle hooks are best suited for this task. This issue arises as I am a beginner prepar ...

Can we create a process that automatically transforms any integer field into a hashed string?

Is there a non-hacky way to hash all IDs before returning to the user? I have explored the documentation extensively but haven't found a solution that covers all scenarios. I am working with Postgres and Prisma ORM, managing multiple models with rela ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

What could be causing npm to fail to launch?

Whenever I execute node app.js, my server functions perfectly. However, when attempting to utilize nodemon for running the server, it fails to start. The error displayed by npm start is as follows: npm ERR! code ELIFECYCLE npm ERR! errno 9009 npm ERR! < ...

Node.js exec command encountering an uninformative error message and not executing properly

Here is the snippet of code that needs to be executed cp.exec("cc -Wall /tmp/test.c -o /tmp/test", function(e, stdout, stderr) { if (e) { var errorstr = "There was an error during compilation: "+ e.message.toString() ...

Error: The OrbitControls function is not recognized in THREE.JS

const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const controls = new OrbitControls(camera); camera.position.set(200, 0, 0); controls.update(); const geometry = new THREE.S ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

Ways to delete a CSS attribute with jquery

Is there a way to eliminate a CSS property from a class without setting it to null? Let's say I have a class called myclass with the property right:0px. I want to completely remove right:0px from my class, not just set it to null. How can I achieve th ...

Enabling individuals to transfer their content to Amazon S3

I have set up an S3 bucket named BUCKET in region BUCKET_REGION. I want to enable users of my web and mobile apps to upload image files to this bucket, with specific restrictions based on Content-Type and Content-Length (specifically, only allowing jpegs u ...

Using HTTPS, you can access Flask from AJAX

I have encountered numerous inquiries concerning this issue, but none have proven effective for me. I recently switched my domain from HTTP to HTTPS. Everything was functioning properly on HTTP. The main issue lies in the fact that my javascript and flask ...

Typescript does not produce unused members

Having an issue with the JS code that TypeScript compiler is generating. Here's an example class: // Class export class UserDTO { Id: number; FirstName: string; LastName: string; DateOfBirth: Date; getFullName(): string { ...

Prevent the box from closing automatically after submitting a form using jQuery

Despite my efforts to keep a simple dialog box open after submitting a form, it continues to close. I tried using the preventDefault method in jQuery, but it didn't solve the issue. Below is the code snippet: $(document).ready(function(e) { $(&apo ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

Using AJAX to call a PHP function within a PHP script

I have successfully implemented an AJAX file that can execute content from a PHP file. However, my concern is how to specifically call a particular function within the PHP file if there are multiple functions present. Below is my current AJAX code: $(doc ...

Utilizing custom links for AJAX to showcase targeted pages: a beginner's guide

I am putting the final touches on my website and realized that it may be difficult to promote specific sections of the site because the browser address never changes. When visitors click on links, they open in a div using Ajax coding. However, if I want to ...

Get your hands on the base64 image by triggering the save as popup and downloading

I am facing a challenge with downloading a base64 image onto the user's machine. So far, I have attempted the following steps: var url = base64Image.replace(/^data:image\/[^;]+/, 'data:application/octet-stream'); window.open(url); an ...