Using Three.js, I implemented a feature that allows the mousewheel to adjust the camera's position vertically rather

I am trying to achieve a specific effect in my Three.js project. I created a scene using the Three.js Editor and downloaded the project with the "Publish" option. By editing the app.js file to import OrbitControls, I have enabled zoom functionality with the mouse wheel. However, I want the mouse wheel to scroll instead of zoom, moving the camera along the Y-axis instead of the Z-axis. Is there a way to achieve this using OrbitControls, or does it add unnecessary complexity? Here is the relevant portion of my app.js:

import {OrbitControls} from './OrbitControls.js';
var APP = {
    Player: function ( THREE ) {
        window.THREE = THREE;
        var loader = new THREE.ObjectLoader();
        var camera, scene, renderer;
        var events = {};
        var dom = document.createElement( 'div' );
        dom.className = "threejs-app";
        this.dom = dom;
        this.width = 500;
        this.height = 500;
        // more code here...
    }
};
export { APP };
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>

Answer №1

Without the specifics of your project, it appears that creating your own stroller module is necessary.

How do we go about this, Teo?

To achieve this task, we simply need to develop a function that facilitates the vertical movement of the camera, as per your request.

So, you're saying that using OrbitControls adds unnecessary complexity?

Indeed, if the sole camera movement required is as you described.

Lets put this plan into action.

Initially, we incorporate

window.addEventListener('wheel', onMouseWheel, false);
to monitor the mouse wheel. Then, we utilize the event.preventDefault(); method to prevent zooming.

Next, we determine the scroll modifier with

camera.position.y += event.deltaY / 1000;
. Here, we employ the delta in the Y-axis. To ensure smooth scrolling, I divided the value by 1000 in this instance.

Finally, we introduce

camera.position.clampScalar(0, 10);
to restrict scrolling beyond specified bounds.

let camera, scene, renderer;
let geometry, material, mesh;

init();
animate();

function init() {
  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);

  camera.position.z = 1;

  scene = new THREE.Scene();

  geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
  material = new THREE.MeshNormalMaterial();

  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });

  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  window.addEventListener('wheel', onMouseWheel, false);
  window.addEventListener('resize', onWindowResize, false);
}


function animate() {

  requestAnimationFrame(animate);

  mesh.rotation.x += 0.01;
  mesh.rotation.y += 0.02;

  renderer.render(scene, camera);
}


function onMouseWheel(ev) {
  event.preventDefault();

  camera.position.y += event.deltaY / 1000;

  // prevent scrolling beyond a min/max value
  camera.position.clampScalar(0, 10);
}


function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>

Answer №2

If you only require vertical scrolling functionality, then there is no need to include OrbitControls as it adds unnecessary complexity. You can easily achieve this by using the default JavaScript APIs:

// Set up a listener for the "wheel" event
window.addEventListener("wheel", onScroll);

function onScroll(event){
    camera.position.y += event.deltaY * 10;
}

The multiplication by 10 depends on the scale of your scene and the desired speed of vertical movement for your camera.

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

Recording audio using Cordova and Javascript

Recently, I've been dabbling in creating a new app using Cordova, VueJs, and Onsen UI for VueJs. One of the main features I want to implement is the ability to use the microphone on Android or iOS devices to record audio and then send it to the Google ...

How to effectively pass data between parent and child controllers in Angular 1 - Seeking guidance

Currently, I am working on two separate applications that have a common requirement of displaying active incidents and closed incidents. Both apps involve similar logic for creating, modifying, saving, and deleting incidents. I am exploring the best appro ...

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 ...

Javascript textfield button function malfunctioning

Here is the code I have created: HTML: <form method="post" id="myemailform" name="myemailform" action="form-to-email.php"> <div id="form_container"> <label class="descriptio ...

Waiting to run a function until a specified function has finished its execution

I have a piece of code that needs to address synchronization issues related to the execution order of MathJax functions. Specifically, I need to ensure that all the MathJax operations are completed before running the setConsoleWidth() function. What is t ...

Controlling the maximum number of components displayed on each row in a loop or map using React

I'm having some trouble with this seemingly simple task and could use some guidance. Any suggestions would be greatly appreciated. Thank you. My Current Situation Currently, I am working with React.js and have an array containing 20 elements. What ...

Successive, Interrelated Delayed Invocations

There are two functions in my code, getStudentById(studentId) and getBookTitleById(bookId), which retrieve data through ajax calls. My ultimate goal is to use Deferreds in the following sequence: Retrieve the Student object, Then fetch the Book Title bas ...

Tips for passing registration form data, uploading images, and implementing validation via Ajax in CodeIgniter

As I work on creating a comprehensive registration form with all necessary data and input tags, I encountered an issue while attempting to pass the image upload value to the next page through AJAX. I need assistance in resolving this problem specifically r ...

Ways to implement CSS with javascript

I'm using PHP to retrieve data from my database and then leveraging Javascript to enable users to add it. However, I am facing challenges in making a div change its background color and apply borders. <div class="displayedItems"></div> &l ...

Enhancing MEAN Stack Application by Updating Table Post Database Collection Modification

In my efforts to ensure that my table data remains synchronized with the database information, I have encountered an issue. Whenever Data Changes: $scope.changeStatus = function($event,label,status){ var target = $event.currentTarget; target ...

Exploring Array Iteration and Incrementing with Easing Techniques

I am currently working on a function that involves iterating over an array and incrementing the values by varying amounts. The challenge is to decrease these incremental amounts as the values in the array get larger. Let's consider the following exam ...

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

Using the `map()` method in React's array

I stumbled upon an interesting example at http://codepen.io/lacker/pen/vXpAgj that closely resembles my current issue. Let's consider the following array: [ {category: 'Sporting Goods', price: '$49.99', stocked: true, name: &apo ...

The specified selector is invalid or illegal in HTMLUnit

Attempting to mimic a login using htmlunit has presented me with an issue despite following examples. The console messages I have gathered are as follows: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' erro ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

I encountered an issue with my node/express server where Res.json is causing a

I am encountering an issue with a 100mb object that I am trying to return using a GET request: function completeTask(req, res) { // generates a large object on a child process, then sends it back to the main process res.json(bigObject); // <--- p ...

Using Google-Prettify with AngularJS

I have been attempting to implement Google Prettify in my AngularJS project. It seems to be functioning correctly on the main page, but once I navigate to another route using Angular (after ng-view), it stops working properly. You can check out the plunker ...

What is the process for sending Raw Commands to a Receipt Printer using Node.JS?

My Current Project I am currently working on integrating a receipt printer that supports ESC/P raw printing into an app for remote printing of receipts. The Approach I Am Taking To achieve this, I am utilizing the PrintNodes API to send data from my app ...

What is the process for incorporating '_BATCHID' into a glTF File?

I am curious about the significance of '_BATCHID' in glTF and how it can be included in a glTF file. I intend to utilize Cesium for rendering .b3dm Files in order to achieve monomerization (singularity). Tools used: Cesium three.js b3dm Thank ...

Assigning index values to child rows in AngularJS: a step by step guide

One of my requirements involves assigning index values to child rows. The structure includes group rows with child rows underneath. Currently, I am using ng-repeat along with $index for the children as shown below: HTML code: <table ng-repeat="nod ...