Implementing a smooth camera movement in Three.js using the mousewheel

Is there anyone who can assist me with achieving smooth camera movement (forward/backward) using the mouse wheel? The current code I have is not providing the desired smoothness.

document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
function onDocumentMouseWheel (event) {
    if (event.wheelDeltaY >= 10) {
        camera.position.z -= 100;
    } else {
        camera.position.z += 100;
    }
}

I would greatly appreciate any help or suggestions. Thank you!

Answer №1

I think I found a solution (I'm not sure if it's the correct way, but it seems to be working)

Within the render function (update)

if (Mouse.moving && Mouse.speed > 0) {
    Mouse.speed -= Mouse.maxSpeed / 20;
    Mouse.smooth();
}

Description of the Mouse object:

var Mouse = {
    moving: false,
    movingForward: null,
    speed: 60,
    timeOfSmooth: 2000, // maxTimeOfSmooth

    wheelListener: function () {
        _this = this;
        _this.maxSpeed = _this.speed; // setting maxSpeed
        document.addEventListener('mousewheel', onDocumentMouseWheel, false);
        function onDocumentMouseWheel(event) {
            _this.speed = _this.maxSpeed;
            _this.moving = true;

            if (event.wheelDeltaY >= 10) {
                _this.movingForward = true;
            } else {
                _this.movingForward = false;
            }

            clearTimeout(_this.timeOut);
            _this.timeOut = setTimeout(function () {
                _this.moving = false;
            }, _this.timeOfSmooth);
        }
    },

    smooth: function () {
        if (this.moving) {
            if (_this.movingForward) {
                Engine.camera.position.z -= _this.speed;
            } else {
                Engine.camera.position.z += _this.speed;
            }
        }
    },

    init: function () {
        this.wheelListener();
    }
};

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

Angular JS - Selecting Directives on the Fly

I'm currently developing an application where users can choose from various widgets using a graphical user interface (GUI). My plan is to integrate these widgets as angular directives. THE CONTROLLER $scope.widgets = ['one', 'two' ...

Use jQuery to compare the input values whenever they are modified

I am trying to synchronize the input values of two inputs as they are typed in. The code I have seems to work sometimes, but not consistently. Here is the code snippet: $('#google-querynav').keypress(function() { var text = $(this).val(); ...

Serving files from a Node.js server and allowing users to download them in their browser

I am facing an issue with my file repository. When I access it through the browser, the file automatically downloads, which is fine. However, I want to make a request to my server and then serve the file result in the browser. Below is an example of the GE ...

Utilizing JavaScript to implement a single method across multiple objects

Recently, I encountered a problem while trying to use the prototype method to apply the same function or variable to multiple objects. Despite creating numerous objects in the following manner: var item = { a: { aa: "lalala", ab: 1, somethin ...

React-Native-SVG encountered an error: Invariant Violation - the component "RNSVGGroup" could not be found in the UIManager

Trying to create an SVG in React-Native using react-native-svg. I have set up a React-Native-CLI. After doing some research, I attempted to solve the issue on my own and found something useful. I tried running cd ios && pod install. I wasn't ...

Sequelize Authentication is unable to finalize

As I delve into the world of node.js and sequelize, I am encountering a persistent error: /home/cbaket/test/test.js:9 .complete(function(err) { ^ TypeError: undefined is not a function at Object.<anonymous> (/home/cbaket/test/test.js:9: ...

Tips for eliminating duplicate entries in ag grid using Angular

Is there a way to eliminate the recurring assetCode entries in ag grid? The PRN and PRN1 values seem to be repeating unnecessarily. Check out the code below: list.component.ts ngOnInit() { this.rowData.push( { 'code': 'Machi ...

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

What is the best way to showcase the chosen items in a dropdown menu?

There seems to be an issue with the selected item not appearing in the input field. export default function BasicSelect() { const [sortBy, setSortBy] = useState(""); const [condition, setCondition] = useState(""); const [delivery, ...

A guide to resolving the error "Unable to find 'require' in vuejs"

I am currently working on a project using vuejs and firebase. I encountered an issue while trying to import firestore. When I accessed my page, I saw this error message in the console: ReferenceError: require is not defined I attempted to place the import ...

When attempting to upload multiple images to my backend, I am consistently receiving an empty array as a result

I have developed an API on the backend that is designed to store images in the database. I have implemented a function for uploading these images, but unfortunately, I am encountering an issue where my database receives an empty array. Interestingly, when ...

How can we showcase the data within this loop on the user interface in React JS?

I'm currently working with React JS and I have a question regarding how to display data from a loop in the UI. The code snippet below shows the data being logged to the console, but I want to show it on the actual user interface. Could you please guid ...

Is there a way to send a variable from a client-side script to a server-side script?

I am facing a challenge in Google App Maker where I am attempting to execute a Client Script to retrieve a variable and then pass that variable to a Server Script for further use. However, I am struggling to figure out the correct implementation. Within m ...

v-autocomplete not displaying full list of items in selection dropdown

I have a question regarding sending an array with values ranging from 1 to 100 on the v-autocomplete item props. However, when scrolling through the list, only numbers up to 40-50 are visible. <template> <v-app> <v-container> ...

Differences between CookieParser and req.cookies in ExpressJS

As I was reading the documentation on req.cookies in expressjs docs, I learned that when the cookieParser() middleware is used, this object defaults to {} but otherwise contains the cookies sent by the user-agent. Then, exploring the details of the Coo ...

Eliminate unnecessary transparency in React Material UI Tooltip / Popper by adjusting opacity restrictions

Looking to integrate the Tooltip component from the React Material UI Library into my project. The code snippet I am using is as follows: <WhiteOnDarkGreyTooltipWithControls disableTouchListener disableFocusListener title={ <Text selectable ...

Is there a way to create an input field that accepts only numbers and behaves like a password field simultaneously?

I am attempting to develop an input field for entering a PIN. I would like the PIN to be masked on mobile devices, similar to how passwords are obscured in password input fields. I came across a suggestion on stackoverflow regarding this, but unfortunately ...

shallow rendering does not recognize this.props as a function

I'm currently facing an issue while trying to test my (legacy) component using jest/enzyme. Here is a snippet of the component: export default class MyComponent extends Component { constructor( props ) { super( props ); this.handl ...

Invoking a function from a separate JavaScript file and finding out that an object is considered null

The source code for a word game is stored in Main.js file. Currently, I am attempting to introduce another file called Bookmarks.js (included on the web page prior to the Main.js file). This new file will contain an object var bookmarks = {}; that stays s ...

animation of several rows in a table with ng-animate is not feasible

I'm working on highlighting items when they appear in a table. There might be multiple items appearing simultaneously, but it seems like ng-animate is not handling this situation correctly. In the provided example below, you can observe that the div ...