Rotating the camera in first person perspective using Three.js

After struggling to find updated help on first player rotation in three.js, I am facing a challenge where most of the solutions provided are using functions that no longer exist in the current library version.

I am attempting to implement a feature where the camera rotates around its own axis based on the position of the mouse cursor on the screen.

The existing rotation code is as follows:

var scale = 10;

function viewKeys(){
  document.addEventListener("mousemove", MouseMove, true);
  function MouseMove(event) {
    mouseX = event.clientX - divOffsetWidth;
    mouseY = event.clientY - divOffsetHeight;
  }
}

The divOffset variables are used to calculate the relative mouse positions to the center of the HTML div.

function viewAnimate(){
  camera.rotation.x = -((3/2)*(Math.PI*mouseY)) / (scale);
  camera.rotation.y = -(2*(Math.PI*mouseX)) / (scale);
}

The viewKeys() function is invoked within the init() function and the viewAnimate() function is called from the animate() function.

Currently, the rotation behaves correctly when the camera is at position (0,0,0), but when positioned elsewhere it appears to rotate relative to the environment's axis rather than its own. While I know there are pre-built control libraries available for three.js, I prefer to understand how to achieve self-axis rotation manually.

Can you provide any suggestions on how I could modify the rotation logic to achieve the desired outcome?

Answer №1

If you're looking to manually rotate the camera using your mouse in three.js, you'll need to have a grasp on how Euler rotations function. For more information on this, check out this detailed answer.

One effective method to achieve your desired outcome is by following a structure similar to the one below:

var scale = 1;
var mouseX = 0;
var mouseY = 0;

camera.rotation.order = "YXZ"; // note that this deviates from the default setting

document.addEventListener( "mousemove", mouseMove, false );

function mouseMove( event ) {

    mouseX = - ( event.clientX / renderer.domElement.clientWidth ) * 2 + 1; // calculating mouse position relative to renderer
    mouseY = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;

    camera.rotation.x = mouseY / scale; // adjusting camera rotation based on mouse movement
    camera.rotation.y = mouseX / scale;

}

I share your sentiment about experimenting with this functionality as it can truly enhance your understanding.

Current version: three.js r.89

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

How to Handle 404 Errors for Specific Express Routes and Not Others

Struggling with the setup of a single page app using Angular routes on the front end, while facing backend issues. All database-related routes are functional, but any additional route designed to serve an HTML file or simple text like "hello world" result ...

What's the best way to add a timestamp and class name to Angular's $log for an enhanced logging experience?

Is there a way to customize Angular logs by adding a timestamp and classname? For example: $log.info('this log entry came from FooBar'); "9:37:18 pm, FooBar: this log entry came from FooBar" I've come across various examples online that ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Find your favorite artist on Spotify through the search function

Recently, I stumbled upon this intriguing demo showcasing how to search for an artist using the Spotify API. However, despite several attempts, I have been unable to make it function properly. Can anyone provide any tips or guidance on making this work suc ...

Are there any libraries available that can assist with managing forms similar to how Google Contacts handles them

By default, Google Contacts has a feature where the form displays values with some of them being read only. However, when you click on a value, it converts the field into an editable form so you can easily make changes. After editing and pressing enter, th ...

Setting an action when clicking on a slice of a Doughnut chart using Chart.js

I have been working on integrating chart.js into my Django Project, and so far it has been going smoothly. I successfully created a doughnut chart with two slices. Now, I am trying to implement separate actions for each slice when clicked, such as redirect ...

A step-by-step guide on extracting all documents within a directory collection from the official national archives website using the R programming language

I'm currently seeking a way to scrape all available files for a data file series on archive.gov programmatically using R. It seems that archives.gov utilizes JavaScript. My objective is to extract the URL of each available file along with its name. T ...

What is the process for transferring an image from the main page to another?

For days, I have been searching for an answer without any luck. It seems that I just can't wrap my head around it and apply it to what I am working on. Currently, I am using PHP to store images on the server when a user hits submit. My goal is to dis ...

Empty screen appears when "npm run serve" command is executed following the build process

I am currently utilizing Material-ui. Following the project build with npm run build, I encounter a blank page when running npm run serve. I attempted to set homepage: "./" in the package.json as suggested here, however, it still displays a blank ...

Ways to Adjust the Earth's Position in WebGL Earth

I have been working with this WebGL Earth component for my project, but I am facing difficulty in adjusting the position of the planet on the canvas. My intention was to place the planet at the bottom of the page, but I haven't been able to achieve th ...

What is the method for enlarging the width of the nvd3 chart timespan?

Click here In the Plnkr linked above, I have included the latest versions of d3 and nvd3 libraries. Upon initial viewing of the chart, you may notice that all the timespan ticks such as 09:00, 08:30, 08:00, etc., are overlapping on the left xAxis. The ti ...

What is the best way to determine if this specific radio button has been selected?

I have been searching for solutions on stackoverflow, but haven't found anything helpful :( Currently, I am facing an issue with my HTML table that is loaded through an ajax request: <table class="table table-striped table-hover choix_annonce_tab ...

Error: Trying to access the length property of an undefined or null reference in JSON formatted data fetched through Ajax

I am attempting to populate a jQuery DataTables with JSON data retrieved from a Web API ajax call, but encountering the following error: An unhandled exception occurred at line 38, column 314 in 0x800a138f - JavaScript runtime error: Unable to get proper ...

What is the most efficient way to transfer form data from one JSP page to another?

I need to transfer information from one webpage (1.jsp) to another webpage (2.jsp). The data that needs to be transferred includes checkboxes, radio buttons, and drop downs. This data will be used in 2.jsp to generate the appropriate page. Is there a way ...

Creating an element that remains fixed once it reaches a distance of 50px from the top of the screen

Hey there! I'm working with an html div element that currently scrolls along with the page, but I was wondering how I can make it become fixed once it reaches a distance of 50px from the top of the screen. Any ideas on how to achieve this? Just to pro ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

Customizing the JavaScript Calendar in Qualtrics

I came across a JavaScript code snippet that allows you to embed a calendar into a Qualtrics question. Specify a date for the survey: <link href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" rel="stylesheet" type="text/css" /> <script sr ...

Creating a Directive in Vue.js to Limit Input Fields to Numeric Values

After recently diving into Vue.js, I encountered a challenge. I needed an input field that only accepted numeric numbers; any other value entered by the user should be replaced with an empty string. To achieve this functionality, I decided to create a cust ...