Disabling Camera Dampening in a 3D Environment Upon Click

I am currently working on a project that involves implementing a damping effect for the camera when the user stops rotating it using their mouse. While this effect is important, I also want to provide users with the option to disable the damping effect by clicking on the screen.

I attempted the following code to disable and re-enable the controls and damping in the onClick event:

this.control.enabled = false;
this.control.enableDamping = false;
this.control.update();
this.control.enableDamping = true;
this.control.enabled = true;

Unfortunately, this approach did not behave as expected. When the user clicks to cancel the damping effect, the camera abruptly shifts to a different position, almost as if it is trying to catch up with the latest update.

If anyone has suggestions on how to achieve the desired behavior, I would greatly appreciate it. Thank you!

Answer №1

To ensure smooth damping, it is important to update the controls within your rendering loop. By checking if damping is enabled and updating the controls conditionally, you can achieve the desired effect.

The code snippet below demonstrates how to toggle damping with a double click:

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

const canvas = document.querySelector('canvas.webgl')

const scene = new THREE.Scene()

const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 'lightblue' })
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)

const width = 800;
const height = 600;

const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 10)
camera.position.set(1, 1, 3);
scene.add(camera)

const controls = new OrbitControls(camera, canvas)
controls.enableDamping = true

const renderer = new THREE.WebGLRenderer({
    canvas: canvas
});
renderer.setSize(width, height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

const renderLoop = () => {
    if (controls.enableDamping) {
        controls.update()
    }

    renderer.render(scene, camera)

    window.requestAnimationFrame(renderLoop)
}

renderLoop()

canvas.addEventListener('dblclick', () => controls.enableDamping = !controls.enableDamping)

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

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

Is there a way to reverse the upside-down text generated by OffscreenCanvas.getContext().fillText()?

When using OffscreenCanvas.getContext().fillText() to generate text and then OffscreenCanvas.transferToImageBitmap() to create a map, I noticed that the text appeared flipped upside down when applied as a texture in a threejs project. The image clearly sho ...

Utilize AngularJS to retrieve and interact with the JSON data stored in a local file once it has

Please do not mark this as a duplicate since I have not found a solution yet. Any help would be appreciated. I have a file called category.json located next to my index.html file, containing the following JSON data: [{"name":"veg"},{"name","non-veg"}] W ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

The issue with window.addEventListener failing to update state when the scrollY is not at zero persists during route changes

When using addEventListener in the componentDidMount lifecycle method to add a class to a header based on the scroll behavior, an issue arises when changing routes via a modal or browser back button. The scrolling state is not accurately reflected as the s ...

Using Vue to create a component that binds an array as its data source

Having trouble binding an array as a variable and accessing it in the child component, resulting in the variable being undefined. Is there a way to pass an array from a view to a component so that the component can use this array to create a child componen ...

Incorporating image hyperlinks onto a designated webpage within a JavaScript presentation carousel

Working on an e-commerce website, the client has requested 3 slide shows to run simultaneously displaying specials or promotions. I have successfully set up the 3 slide shows next to each other, but I'm unsure how to incorporate image links that direc ...

What steps should I take to ensure that this JSON.stringify function functions as intended?

I'm facing a minor challenge in formatting my arrays into the desired JSON structure. Here's the code I've used: var arrData = [{label:Test,value:199.12}, {label:Test2,value:1024}] var data = []; for (var i = 0; i < arrData.length ...

Conceal two DIV elements if one of them is empty

My slideshow has thumbnails connected to each slide. There are 10 DIVs representing the slides like this... <div class="SSSlide clip_frame grpelem slide" id="u751"><!-- image --> <?php while ($row = mysql_fetch_array($query ...

What is the best way to insert data from a promise into MongoDB?

While attempting to integrate an array of JSON data from a different server into a MongoDB collection, I encountered the following error message: "Cannot create property '_id' on string". Even though I am passing in an array, it seems to be causi ...

React - Error: Unable to access the 'props' property because it is undefined

I am working on implementing a click event to delete an item from my list, but I keep encountering the error message "TypeError: Cannot read property 'props' of undefined" whenever I click on it. Although I am striving to follow ES6 standards as ...

Utilizing a string as an argument in a function and dynamically assigning it as a key name in object.assign

Within my Angular 5 app written in TypeScript, I have a method in a service that requires two arguments: an event object and a string serving as the key for an object stored in the browser's web storage. This method is responsible for assigning a new ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Issue with URL parameter in React when using React Router

Initially, everything was running smoothly in my React project using react-router-dom. However, once I added another Route like so: <Route path="/edit/:id" component={EditPage}/> and tried changing the URL in the browser to http://localhos ...

When running npm install -g, the package is being installed into a global directory on

For a considerable amount of time, I have been working with node and npm. Now, as I embark on a more extensive project using these tools, I've encountered an issue. Whenever I execute 'sudo npm install -g', the installation is directed to &a ...

Implementing a download hyperlink attribute for a button with jQuery

How can I create a jQuery function for a button? <input type="submit" id="submit"></input> Once clicked, it should trigger the following action: <a download href="file.doc"></a> <script> $("#submit").click(function(){ ...

The sorting process fails to make any changes, thus leaving the state unaffected

Is there a way to sort an array of objects in descending order by their id? No errors appear in the console. Even after calling the sort method, the state of allPosts remains unchanged. import { useState } from "react"; import Button f ...

Combining two arrays by finding common elements

Currently, I am working on a project where I retrieve data from the server, and each piece of data has to adhere to a specific format: const DATA = [ { title: {title: 'Main dishes'}, data: [ {_id: 1, type: 'Pizza'}, ...

I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing? angular.module('app', []); an ...

Performing a map or foreach function on an array of objects limited to the first 5 objects

I need to iterate through an array of objects, but I only want to loop through the first 5 objects and then stop. What is the most efficient way to achieve this? [ {"visibility": 10000,}, {"visibility": 10000,}, {"visibilit ...