Three.js elements are not appearing in the scene because the camera is not properly positioned

In my scene, I have a variety of elements such as a cube, cylinder, sphere, and more. The camera is positioned at (0,30,40) to display the entire scene, but I'm encountering issues with one specific element - a moving cube.

When I try to use the camera position (0,30,40) for the cube, it doesn't align correctly. However, if I change the camera position to (0,-400,400), the cube displays properly. This discrepancy can be seen in lines 30-32 of the JavaScript code below.

     var angularSpeed = 0.2;
            var lastTime = 0;

            function animate(){
                var time = (new Date()).getTime();
                var timeDiff = time - lastTime;
                var angularChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
                cube.rotation.y -= angularChange;
                lastTime = time;

                renderer.render(scene, camera);

                requestAnimationFrame(function(){
                    animate();
                });
            }

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(window.innerWidth, window.innerHeight);
            document.body.appendChild(renderer.domElement);

            var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);

            /* Works */
            camera.position.x = 0;
            camera.position.y = -400;
            camera.position.z = 400;

            /* Does not work, but I want these to be the camera settings */
//            camera.position.x = 0;
//            camera.position.y = 30;
//            camera.position.z = 40;

            camera.rotation.x = 0.70;

            var scene = new THREE.Scene();

            var cube = new THREE.Mesh(new THREE.CubeGeometry(200,100,100), new THREE.MeshNormalMaterial());

            scene.add(cube);

            animate();

To view the same code in JSBin, click here.

I am seeking advice on how to address this issue. While I can adjust the cube's position using its APIs, tweaking cube.position.x, cube.position.y, and cube.position.z, it involves trial and error when working with specific camera settings like (0,30,40).

In an attempt to centralize multiple elements regardless of the camera position, I created a scene with various objects. Despite achieving success by modifying the cube's y position or dimensions, I question whether this method is feasible when all three coordinate axes require adjustment. Is there a more efficient solution?

Considering suggestions to use camera.lookAt(cube.position) raises concerns as I aim to focus on not just the cube but other elements like the cylinder, sphere, plane, polyhedron, torusknot, and torus within the same scene.

Answer №1

Adjust the camera to focus on the position of the newly added cube within the scene:

camera.alignToCube(cube.position);

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

What is the process of memory allocation for variables in Javascript?

Can you explain to me how local variables are allocated memory in JavaScript? In languages like C and C++, local variables are typically stored on the stack. Is this also the case with JavaScript, or are all variables stored in the heap? ...

Enhancing data rendering by incorporating extra verifications through the logical AND operator to prevent crashes upon page refresh

Upon refreshing the page, my app crashed. The issue stemmed from the page loading faster than my data, prompting me to include additional checks using the logical AND operator. While effective in preventing crashes, this approach seems laborious and begs t ...

I'm thinking about transitioning my current React app to Next.js. Do you think it's a good move?

We have recently transitioned our project from react-redux with firebase authentication and solr DB to next.js. Below is the updated folder structure of our app: --src --actions --assets --components --controllers --firebase --redu ...

Winston is set up to only record .info errors and does not save any errors to a file or a MongoDB database

Currently, I am utilizing express-mongoose as my backend framework and winston as my logging tool. However, I have encountered an issue where winston only seems to log info messages and not errors. The logs can be found in server.log https://i.stack.imgur. ...

Exploring an Array Based on User's Input with JavaScript

Looking to implement a search functionality for an array using AJAX. The array is pre-populated with values, and the user will input a value in a HTML text box. If the entered value is found in the array, it should display "Value found", otherwise "not f ...

Automatically use JavaScript to send an email to my email address

I have a question I'm trying to solve: Is there a way to send myself an email notification (using a different address) when a specific event occurs in Javascript or Node.js? For example: if (100 > 90) { emailto="xxxxx.gmail.com" subject="It happ ...

The continuous firing of the postback event of the Asp.Net Button is

Why does the postback event keep firing for my button? Strangely, when I try to debug with Firebug and set a break point on the function(e) part, the code seems to skip right over it. Even using return false doesn't seem to resolve the issue. <sc ...

Seeking advice on modifying the background color within the code? (Designer delving into the coding realm)

Seeking guidance on changing the background color within this code. (designer navigating the coding realm) <script src="https://cdn.rawgit.com/mrdoob/three.js/fdefb19b/examples/js/renderers/CanvasRenderer.js"></script> <script src="https ...

Restricting href Usage Based on Session

I find myself in a challenging situation without a clear solution at hand. Within this code, I am utilizing a link and a button for which I need to save the page in a database. Therefore, creating a server control is not an option as it will not be render ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...

The DataType.MultilineText field in my modal popup partial view is causing all validation to fail

I encountered a peculiar issue recently. After creating a new asp.net mvc5 application, I decided to upgrade it to asp.net mvc-5.2.2. The problem arose with the following field:- [Required] [StringLength(200)] public string Name { get; set; } When ren ...

Guide to effectively pass router properties in a Modal/Dialog component within a React application for seamless navigation

I have encountered an issue with my React-Project. I integrated a login component in a modal/dialog form, and the button to access it is located within the Header component of the project. However, I did not set a router path for the login module, which is ...

What is the best way to access a variable from a .js file?

Is there a way to access a variable defined in a JavaScript file from a Vue file and pass it to the Vue file? In the following code snippet, there is a template.js file and a contact.vue file. The template file converts MJML to HTML and saves the output to ...

Order the JavaScript object by its value if the keys are numerical

I'm currently working on a project using InertiaJS. I have a PHP array that I pass as a prop to Vue and display it as a select box. Here's what the object looks like in JavaScript: { 1: "Vexapa", 5: "Linga & Satro", ...

Return to a mention of a tree reference

Here is an example code snippet: <table> <tr> <td></td> <td></td> <td> <table> <tr> <td><a href="#" class="fav">click me</a></td> ...

Tips for retrieving the return value from a function with an error handling callback

I am having an issue with my function that is supposed to return data or throw an error from a JSON web token custom function. The problem I am facing is that the data returned from the signer part of the function is not being assigned to the token const a ...

Guide on how to optimize an ajax call in the browser to prefetch JSON data

One scenario I am dealing with involves initiating multiple ajax calls upon page load. The first call fetches data in JSON format from the server, and subsequent user interactions trigger further ajax requests that require database queries to process the J ...

Experiencing issues with npm while debugging: Error code ELIFECYCLE and error number 1 have occurred

Seeking guidance on troubleshooting this compiler error: npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! ******@1.1.0 dev: `NODE_ENV=development ts-node ./src/server.ts` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the ******@1.1.0 dev script. n ...

Finding the distance between two points in JavaScript requires a simple formula

Here is a code snippet that generates two TRACER points and displays them on a map, as well as shows the union between the two points. <?php $latitudInicio = $_GET['latitudInicio']; $longitudInicio = $_GET['longitudInicio']; $latit ...

Utilizing a universal JavaScript array within the jQuery document(ready) function

After using jsRender to render the following HTML template, I encountered an issue with passing data values through jQuery selectors when submitting a form via AJAX. <div class="noteActions top" style="z-index: 3;"> <span onclick="noteAction(&a ...