Navigating with the mouse in THREE.js

Big shoutout to the amazing Stack Overflow community for always being there to help budding coders like myself!

I've successfully implemented first-person camera movement in my project, allowing me to navigate forward, backward, sideways, and rotate using arrow keys. Now, I'm looking to enhance the experience by enabling mouse look functionality - the ability to click and drag to look sideways, up, and down. I've tried using three.js-pointlocker and first-person controls, but they didn't quite meet my requirements. Is there a way to implement mouse look alongside my existing keyboard movements?

For keyboard movements, I've been using THREEx.KeyboardState.js by stemkoshi:

var delta = clock.getDelta();
var moveDistance = 50 * delta; // 200 pixels per second
var rotateAngle = Math.PI / 2 * delta;  

if ( keyboard.pressed("W") || keyboard.pressed("up"))
    camera.translateZ( -moveDistance );
if ( keyboard.pressed("S")|| keyboard.pressed("down"))
    camera.translateZ( moveDistance );
if ( keyboard.pressed("Q") )
    camera.translateX( -moveDistance );
if ( keyboard.pressed("E") )
    camera.translateX( moveDistance );

var rotation_matrix = new THREE.Matrix4().identity();
if ( keyboard.pressed("A")|| keyboard.pressed("left") )
    camera.rotateOnAxis( new THREE.Vector3(0,1,0), rotateAngle);
if ( keyboard.pressed("D")|| keyboard.pressed("right") )
    camera.rotateOnAxis( new THREE.Vector3(0,1,0), -rotateAngle);
if ( keyboard.pressed("R") )
    camera.rotateOnAxis( new THREE.Vector3(1,0,0), rotateAngle);
if ( keyboard.pressed("F") )
    camera.rotateOnAxis( new THREE.Vector3(1,0,0), -rotateAngle);

if ( keyboard.pressed("Z") )
{
    camera.position.set(0,17,0);
    camera.rotation.set(0,0,0);
}

Answer №1

Enhanced Version (Even Easier!)

View the working demo on CodePen.

  1. a. Set up a mousedown event listener to capture the initial mouse position (event.clientX, event.clientY) as startX and startY.

    b. Inside the mousedown function, add a mousemove event listener.

    c. Implement a mouseup event listener to remove the mousemove listener.

  2. a. Within the mousemove function, store the new mouse coordinates newX and newY. Adjust camera.rotation based on newX-startX and newY-startY. In the provided example, this is demonstrated as:

    camera.rotation.x += newY - startY;
    camera.rotation.y += newX - startX;
    

    b. Update startX to equal newX, and set startY to newY.

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

Tips for spinning a gltf model as you scroll through the webpage

I am currently working on achieving a smooth rotation of a gltf model while scrolling. I have successfully developed a function that converts pageYOffset from pixels to radians let scrollPositionRad = 0; window.addEventListener("scroll", onWindowScroll ...

Using Javascript within a PHP file to generate JSON output

Can you integrate Javascript code within a PHP file that utilizes header('Content-Type: application/json'); to produce output in JSON format? UPDATE: I'm attempting to modify the color of a CSS class when $est = 'Crest', but the J ...

By incorporating JavaScript, clicking on an image will trigger a shift in the position of a different element

Just starting out with JavaScript and experimenting with creating an event where clicking on an image triggers the movement of another hidden image. The hidden image is positioned off-screen to the left, while there is a table of images in the center of th ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

Remove any list items that do not possess a particular class

My ul list contains several lis, and I need to remove all li elements that do not have children with the class noremove. This is the original HTML: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>I ...

Personalize the "spirit" component using VueDraggable

I am currently utilizing the library found at: https://github.com/SortableJS/Sortable In my project, I have 2 lists where I can drag one element to the other list. However, when I drag the item, it appears as a clone of the icon. My goal is to have a cust ...

What could be the reason for the undefined initial state in my vuex store?

I am facing an issue with vuex-typescript where the initial state is always undefined. However, it works fine when I reset the state and refresh the window. Below is my setup for a simple module: import Vue from "vue"; import Vuex from "vuex"; import { m ...

The function window.open when using the target '_blank' will launch a fresh browser window

I'm attempting to open a link in a new browser tab (not a new window). When I place a link on the page like this: <a href="#" onclick="window.open('http://www.google.com', '_blank');"> Click Here</a> when a user clic ...

Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock. What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling ...

Changing the name of a radio button dynamically using jQuery

Trying to find a solution like the following: $("input:radio:checked").previous("name", "original_name").attr("name","new_name"); I've experimented with a few methods found here, but keep encountering the error: Object Expected Any assistance would ...

React - Anticipated an assignment or invocation of a function

Recently starting my journey with reactjs and encountered a small issue. A pesky error keeps popping up saying: Expect an assignment or function call. It's related to the User function, however, I do call that function when creating a new object. Any ...

What causes the source code of a website to change when accessed from various browsers?

When analyzing the source code of bartzmall.pk using various browsers, it reveals different classes being added to the html tag for each browser. For Firefox: <html class="firefox firefox53 otherClasses"> For Chrome: <html class="webkit chrome ...

What is the best way to retrieve the first item in owl carousel's content?

I need help creating a slider with two sections: top and bottom. My goal is to display the content from the bottom slider on the top slider. I tried adding a class to the first item element, but it didn't work. If anyone knows how to target the first ...

Error message: The Next.js GraphQL-Yoga server is returning a 404 error on the

I am brand new to using graphql-yoga 3 in conjunction with next js for creating APIs with GraphQL. Unfortunately, my routes at /api/graphql are returning a 404 error even though I have followed the example provided here. The default page loads fine, but I ...

The component fails to display on the page when using Vue-router

I'm having an issue with my router. I'm trying to display bodyComponent on my index page, but nothing is happening. I'm using laravel+vue. Can anyone point out where I might be going wrong? Here's my router: import Vue from 'vue& ...

Tips for managing asynchronous code that invokes other asynchronous code in AngularJs

My factory utilizes indexedDB and a method called getRecipe that relies on this indexed db to fetch data. The issue arises because indexedDB returns its instance in an asynchronous call, and getRecipe is another method that also returns its value asynchro ...

Interactive Component overlying Layer - HTML/CSS

Currently, I am working on a web application that features a navigation bar at the bottom of the screen. To enhance visibility, I decided to apply a linear gradient overlay above the underlying elements. This screenshot illustrates what I mean. However, I ...

What steps can be taken to prevent an event from being triggered once it has already started but has not yet concluded?

Let's talk about the navigation bar on the website. Clicking on it toggles the menu holder to slide in and out from the side. It's a simple interaction. The bar contains an icon with the text 'MENU'. When you open the menu, the icon cha ...

Guidance on changing the user's path within the same domain using a button click in express

Currently, I am working on a basic web application where I need to implement a feature that redirects users to different paths within my project upon clicking a button. My project consists of two versions - one in English and the other in Polish. I am util ...

Encountering the error message "Angular 'undefined is not a function' when trying to define a component

My Ionic code was originally working fine, allowing the user to input a list. I decided to refactor it into a component for re-usability but encountered an error undefined is not a function on line 4 of the Javascript file. How can this issue be resolved? ...