Moving the camera in Three.js to focus on a specific point

Currently, I am in the process of developing a website utilizing three.js technology. For a preview, you can check out the demo by visiting: . The website is designed on canvas to ensure compatibility with iOS and Android devices.

My main query pertains to how I can smoothly transition the camera from its initial position to the location of an object that has been clicked. Is there a more efficient method than using the translate function separately on each axis?

Appreciate your insights!

pp

Answer №1

const handleMouseClick = (event) => {
    event.preventDefault();

    const vector = new THREE.Vector3(
        renderer.devicePixelRatio * (event.pageX - this.offsetLeft) / this.width * 2 - 1,
        -renderer.devicePixelRatio * (event.pageY - this.offsetTop) / this.height * 2 + 1,
        0.5
    );
    projector.unprojectVector(vector, camera);

    const raycaster = new THREE.Raycaster(
        camera.position,
        vector.sub(camera.position).normalize()
    );
    const intersects = raycaster.intersectObjects(YOUR_CLICKABLE_OBJECTS);
    
    if (intersects.length > 0) {
        camera.position.copy(intersects[0].point);
        // Alternatively: camera.position.copy(intersects[0].object.position.clone());
    }
};

renderer.domElement.addEventListener('mousedown', handleMouseClick, false);

This script:

  • Attaches an event listener to detect mouse clicks
  • Translates the 2D click location into a corresponding 3D position in the scene
  • Projects a virtual line (ray) from the camera towards the clicked spot
  • Determines if any objects intersect with the ray and moves the camera to the first intersection point

If you prefer a gradual transition of the camera to the clicked location instead of an abrupt jump, consider utilizing a tweening library such as TweenJS for precise control over the animation timing.

(P.S.: The use of renderer.devicePixelRatio might only be necessary for WebGL renderers; feel free to omit it for other renderers.)

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

Having trouble grasping the problem with the connection

While I have worked with this type of binding (using knockout.js) in the past without any issues, a new problem has come up today. Specifically: I have a complex view model that consists of "parts" based on a certain process parameter. Although the entire ...

Vue: restrict entry to the view unless props are configured

Currently, I am in the process of creating a Vue game that consists of two main views: a 'setup' view and a 'play' view. The values that are configured in the setup view are then passed as props to the play view, initiating the game wit ...

The challenge of transferring documents to the server

There is a form on the webpage where users can select a file and click a button to send it. <form enctype="multipart/form-data"> <input type="file" id="fileInput" /> <button type="button&quo ...

What is the process for implementing npm packages in Laravel after they have been successfully installed?

After installing npm packages in Laravel, how do I require them? For example, let's say I need the package sweetalert2. To install it, run the command: npm install --save sweetalert2 Now, do I need to include it in the \resources\assets ...

Is Consistency Possible with CSS Transition Direction?

Take a look at this example: https://codepen.io/jon424/pen/XWzGNLe In the provided code snippet, there is a button that can toggle the visibility of an image. When clicked, the image disappears from bottom to top and reappears when clicked again. The use ...

Using AJAX to submit a form and then refreshing the page within the current tab

I am facing an issue with my web page that contains multiple tabs, some of which have forms. Whenever a form is successfully submitted, the page reloads but always goes back to the default first tab. To address this, I am attempting to use a storage variab ...

How can I access the feed of a single user using the Facebook API

I have yet to experience working with Facebook APIs, but I am interested in developing a basic app that will display posts from a specific Facebook user. I would prefer not to enable login for multiple users, just keep it simple. My goal is to create an a ...

Puppeteer - How to manage a basic authentication prompt that pops up after clicking a link

I need assistance with handling a basic authentication popup using puppeteer=5.2.1. My specific scenario is outlined below. 1. Start an application 2. Click on a button on the home page 3. This action opens a new window (saml) requesting email input Withi ...

GraphQL Shield throws an 'Unauthorized' error for a permitted mutation

I've been working on setting up a GraphQL API with apollo-server-express, and I'm trying to handle permissions using graphql-shield middleware. However, I'm running into some issues when it comes to allowing mutations to be executed. My aim ...

Searching for nicknames in a worldwide Jest arrangement?

Before running all test cases, I need to execute certain tasks only once. To achieve this, I have created a global function and specified the globalSetup field in my Jest configuration: globalSetup: path.resolve(srcPath, 'TestUtils', 'global ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

Getting an image file to an API server using Node.js

I am looking to create an API server using node.js, and one of the requirements is to upload image files to it. While I have successfully implemented the logic for the GET method in my code, I am struggling with how to write the logic for the POST method ...

Increasing the value of a food topping element within a v-for list of toppings when clicking on the "+ add" button in Vue

I'm a newcomer to the world of JavaScript and Vue.js, currently working on a project to automate the ordering process for my pizza delivery pizzeria. On the website, I have a list of toppings that customers can choose from. They have the option to se ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...

Retrieving Files from POST Request Body Using Node.js and Angular

Currently, I am developing a MEAN Stack application and facing an issue while handling a form that should allow users to upload a file upon submission. The process seems to work seamlessly on the client side; however, when I inspect the request body after ...

JQuery: Techniques for accessing the assigned font of an element

Can the assigned font of an element be retrieved using jQuery? For example, if there is this CSS: #element { font-family: blahblah,Arial; } In the above case, the Arial font will be assigned to #element. Is it possible to extract that information using ...

Choose a text input form field simultaneously?

Is it possible to create a select field that also acts as an input form simultaneously? I need the options in this hybrid field to range from 0.01 to 10.00, while ensuring it always displays 2 decimal places. Curious how I can achieve this functionality ...