Switching camera view on mouse click with three.js

I am new to three.js and apologize if my question is a bit complex.

I have set up my scene in three.js but now I want the camera's position to smoothly transition from point A to point B (which I will specify in my code). I plan on using Tween.js to help with the camera animation.

What I am looking for is for the camera's position to change every time the left mouse button is clicked. Essentially, I want the camera to toggle between position A and position B whenever the left mouse button is clicked anywhere in the scene.

However, I am unsure how to achieve this specific functionality. I have found tutorials on changing positions while the mouse is held down, but not on toggling back and forth between fixed positions when the mouse is clicked. Could it be as simple as adding an 'if' statement within the render() function that changes the camera position upon a mouse click?

Any guidance would be greatly appreciated.

EDIT:

Below is the code snippet for my render() scene:

function render() {

            var timer = Date.now() * 0.00030;

            camera.position.x += ( 0.5*Math.sin( timer ) * mouseX - camera.position.x ) * 0.05;
            camera.position.y += ( 0.5*Math.cos( timer ) *- mouseY - camera.position.y ) * 0.05;
            camera.position.z = 0;

            camera.lookAt( scene.position );

            for ( i = 0; i < scene.children.length; i ++ ) {
                var object = scene.children[ i ];
                if ( object instanceof THREE.Points ) {
                    object.rotation.y = time * ( i < 4 ? i + 1 : - ( i + 1 ) );
                }
            }

            for ( i = 0; i < materials.length; i ++ ) {
                color = parameters[i][0];
                h = ( 0 * ( color[0] + time ) % 360 ) / 360;
                materials[i].color.setHSL( h, color[1], color[2] );
            }

            renderer.render( scene, camera );

        }

To clarify, my goal is to animate camera.position.z = 0; to a different specified position everytime the left mouse button is clicked in my scene.

Answer №1

To track mouse events on the document, change the position, and then execute render() to refresh the canvas.

// array containing different positions in [x, y, z] coordinates
var positions = [
  [0, 0, 0],
  [5, 0, 0]
];

// initialize with the first position
var positionIndex = 0;
var position = positions[positionIndex];

document.addEventListener('click', function() {
  // update position on click event ...
  positionIndex++;
  // reset position index to 0 if it exceeds array length
  positionIndex = positionIndex >= positions.length ? 0 : positionIndex;
  
  // update current position
  position = positions[positionIndex];
  
  // redraw the canvas
  render();
});

function render() {
  console.log('rendering at position', position);
}


// initial rendering
render();

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

Visit a webpage on my site

Is it feasible to embed a website within another website? Suppose I have my index.html file. What if in the center of that file, we include an iFrame or similar element that loads , allowing users to explore Google directly on my website? ...

Determine if I'm actively typing in the input field and alter the loader icon accordingly with AngularJS

Just delving into the world of AngularJS and attempting to tweak an icon as I type in an input box. Currently, I can detect when the box is focused using the following code: $scope.loading = false; $scope.focused = function() { console.log("got ...

Combining Two DIVS Side by Side

Hey there, I am working on a timeline using two divs within a table cell. My goal is to have these divs overlap instead of appearing one below the other. The position attribute for all the DIVs inside the cell must remain unchanged due to the drag/drop fu ...

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

I just made an ajax call. Now, how should I proceed with formatting the data that was returned

The ajax request below is functional, but not without its challenges. Working with HttpContext has proven to be difficult, as even Context.Response.Clear() does not seem to have any effect. How can I output only the desired content without any extra infor ...

Firebase (web) deploy encounters an issue due to stripe integration

I recently integrated Stripe into my Firebase function index.js: const stripe = require('stripe')('key'); and created a function for checkout sessions: exports.createCheckoutSession = functions.https.onCall(async(data, context) =&g ...

Rotating an HTML caret using CSS does not pivot from the center point

Is there a way to adjust my simple caret rotation to make it rotate from the center? What changes should I make? const Wrap = styled.div` width: 100px; background: grey; span { display: block; transform: ${(props) => (props.isOpen ? " ...

Encountering a ReferenceError in React-Native with abcjs library: Element variable not found

import abcjs from 'abcjs'; export default class MusicScore extends Component { constructor(props) { super(props); this.state={ data: this.props.navigation.getParam('abctune'), } } render( ...

Error: Browserify jQuery Plugin Not Working

Having trouble browserifying a jQuery plugin and keep seeing this error in the browsers console: Uncaught Error: Cannot find module 'jquery' Here's how I have my package.json set up: "browserify": { "transform": [ "browserify-shim" ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...

Tips on choosing filters and leveraging the chosen value for searching in a Vue application

I am currently working on a Vue JS application that allows users to apply filters and search a database. The user can select or type in filters, such as "to" and "from", which are then used in a fetch URL to retrieve data from a json-server. Once the user ...

mentioning someone using the @ symbol

I am currently in the process of creating a tagging system for users. I have almost completed it, but there is one issue that I cannot seem to figure out. I know what the problem is, but I am struggling to come up with a solution. When I input the @ sign ...

Selenium htmlUnit with dynamic content failing to render properly

My current project involves creating Selenium tests for a particular website. Essentially, when a user navigates to the site, a CMS injects some dynamic elements (HTML + JS) onto the page. Everything works fine when running tests on the Firefox driver. H ...

Employing useEffect within Material-UI tabs to conceal the third tab

At the page's initial load, I want to hide the first two tabs. The third tab should be visible with its content displayed right away. Currently, I can only see the content after clicking on the third tab. To troubleshoot this issue, I attempted to use ...

Text transitions in a gentle fade effect, appearing and disappearing with each change

I want to create a smooth fade in and out effect for the text within a div when it changes or hides. After researching on Google and Stack Overflow, I found that most solutions involve adding a 'hide' CSS class and toggling it with a custom func ...

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

Exploring the properties within a MongoDB document using mapping functionality

I am trying to retrieve data from a document using Node.js and encountering an issue where the map operator is returning data with similar names twice. I am wondering if I can use filter instead of map to address this problem. Here is the code I am using t ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

Disabling the movement of arrows in the client-testimonials-carousel plugin

This plugin that I'm currently using is working flawlessly: However, I'm unsure about how to make the arrows stationary and prevent them from moving. Currently, they are centering themselves based on the height of the div, but I want them to rem ...

Identical IDs appearing in multiple buttons causing a conflict

I am currently loading content from external HTML files, specifically page1.html and page2.html. Although everything is the same except for the pictures and text, I am encountering an issue with the close button. It only closes page1.html.Feel free to chec ...