Adjust THREE.PerspectiveCamera's distance without altering its viewing orientation

I have a PerspectiveCamera in THREE.js positioned somewhere in space as a child of a mesh. The camera is currently looking at the mesh with local coordinates [0, 0, 0]. I am looking for a way to change the distance of the camera from the mesh without changing the viewing direction. Is there an easy method to achieve this?

camera.position.z = 13 // This only works if position.x and position.y are 0.
camera.setDistanceFromTarget(13) // I wish there was a method like this.

I am considering manually calculating the actual camera's rotation angles and the new camera position. You can find a working example here.

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 geometry = new THREE.BoxGeometry(3, 3, 3);

var cube = new THREE.Mesh(geometry);
scene.add(cube);
cube.add(camera);

camera.position.set(2, 4, 6)
camera.lookAt(cube.position)

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

animate();

// How can we set the camera's distance from [0, 0, 0] to 13 without altering the view direction?
camera.position.z = 13;
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>THREE.js camera demo</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js"></script>
</body>
</html>

Answer №1

To achieve the desired outcome, it is important to ensure that the camera position vector is normalized and then scaled by the intended length using a scalar multiplication method:

camera.position.normalize().multiplyScalar(13)

[ https://jsfiddle.net/3kgjrtu9/ ]

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

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Guide to sending an ajax request from one page and receiving the response on a different page

Looking for advice on sending Ajax requests using jQuery and HTML5. I have multiple pages within my application. Is it possible to send an Ajax request from one page (e.g sync.html) and receive a response on another page (e.g home.html)? I am aware of alte ...

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed https://i.sstatic.net/YkHp0.png I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.d ...

JavaScript | Calculating total and separate scores by moving one div onto another div

I have a fun project in progress involving HTML and Javascript. It's a virtual zoo where you can drag and drop different animals into their designated cages. As you move the animals, the total count of animals in the zoo updates automatically with the ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

Enhance the sequence of tweens by triggering them sequentially in response to rapid UI events

I am currently working on my three.js app setup and I am facing a challenge with creating a smooth transition between two models. The desired effect is to have the first model quickly scale down to zero, followed by the second model scaling up from zero t ...

Unable to detect click event in Vue devtools

My component is supposed to detect if a menu item has a submenu and toggle its visibility accordingly. However, when I click on it, nothing happens and no event is registered in the Vue devtools. Despite following the Vue docs closely and using the same sy ...

The issue of slides overlapping in a Javascript slideshow during auto play mode

I encountered an issue while creating an automatic slideshow with 4 slides. Upon autoplay for the first time, slide 1 overlaps slide 4, as well as slide 2 and 3. This only happens once after the site loads. However, on subsequent playthroughs or when using ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

Ways to troubleshoot NPM installation issues related to gyp ERR

I have tried most of the suggestions found online, but I am still encountering an error when trying to install opencv and serialport. My current setup includes Visual Studio 2019 with C++ Desktop environment and Python 3.7. npm ERR! command C:\Windows ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

Tips on navigating the scroller vertically as the user interacts with a selected div by scrolling up and down

On my webpage, I have various div elements displayed. Each div has the options to move it up or down using the buttons labeled "UP" and "Down". When a user selects a div, they can then use these buttons to adjust its position. I am looking for a way to au ...

Resolving the Angular5 (Angular Universal) problem with page source visibility

Currently tackling a server-side rendering project, inspired by the Angular Universal guide. Everything seems to be on track, but I'm facing an issue where even when navigating to different routes, the source code for the initial page is displayed whe ...

The damping effect in three.js OrbitControls only activates when the mouse is pressed, however there is no damping effect once the

I find it difficult to articulate: Currently, I am utilizing OrbitControls in three.js and have activated damping for a smoother rotation with the mouse. It is somewhat effective but not entirely seamless. When I click and drag, the damping feature works ...

What causes json.parse to malfunction? and how can you resolve the issue

My server sends data to my JavaScript code in the format below. {"triggers": [{"message_type": "sms","recipients": "[\"+91xxxxxxxxx\",\"+91xxxxxxxxx\"]", "message": "This is a test"}]} To parse this JSON string, my code executes the f ...

What is the best way to integrate a React component into an Angular project?

Struggling with integrating a React component into an Angular project and unable to make it work. I have a JavaScript file containing the React component that I want to use in Angular. Here's an example: React file... import React from "react"; c ...

What is the best way to dynamically adjust the top CSS of an element when it is positioned at the top or

Is there a way to dynamically set the top CSS when an element is over the top or bottom of a page? First, hover over the first cat image. It's working fine. http://image.ohozaa.com/i/480/7YpWei.jpg When I scroll the page to the bottom and hover ove ...

Tips for integrating Redux toolkit with the latest version of Next.js

It seems that in order to incorporate redux into my app, I must enclose the majority of it within a redux provider, which should be a client component. As a result, almost every part of my app becomes a child of this client component. Does this imply tha ...

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...