Rotating objects with the keyboard in Three.js

Searching for assistance to rotate a 3D object along the y-axis with a keyboard input (B). Anyone available to help?

I've been struggling with this issue for days now, every attempt at coding leads to errors.

Please, any help would be greatly appreciated.

This is the 3D object that requires rotation

Here is the code snippet:

var lesson6 = {
  scene: null,
  camera: null,
  renderer: null,
  container: null,
  controls: null,
  clock: null,
  stats: null,


  init: function() { // Initialization



// Rest of the initialization code here...

},
  loadModel: function() {

// Loader and model loading code...

}});
  }
};

function animate() {
  requestAnimationFrame(animate);
  render();
}



function render() {
  if (lesson6.renderer) {
    lesson6.renderer.render(lesson6.scene, lesson6.camera);

    }
  }



function initializeLesson() {
  lesson6.init();
  animate();
}

if (window.addEventListener)
  window.addEventListener('load', initializeLesson, false);
else if (window.attachEvent)
  window.attachEvent('onload', initializeLesson);
else window.onload = initializeLesson;

Answer №1

When working with such input, it is important to ensure that button presses do not directly modify any object. Instead, keyup/keydown/other input events should be kept simple: toggling a true/false variable or adjusting a number.

Consider the following example:

function handleKeyDown(event) {
  if (event.keyCode === 66) { //66 represents "b"
    window.isBDown = true;
  }
}

function handleKeyUp(event) {
  if (event.keyCode === 66) {
    window.isBDown = false;
  }
}

window.addEventListener('keydown', handleKeyDown, false);
window.addEventListener('keyup', handleKeyUp, false);

With this setup, you can then update your animate() function as follows:

function animate() {
  requestAnimationFrame(animate);
  if (window.isBDown) {
    //Increment the Y rotation value of your object slightly.
    //You may also consider using the high resolution timestamp provided by animate()'s first argument.
  }
  render();
}

Notice how all the action takes place within animate(). By setting the appropriate speed, the object will rotate gradually until the key is released. Once you are comfortable with this approach, you can explore adding acceleration and momentum to animate().

Gamepad joysticks operate in a similar manner, but instead of a binary true/false state, they provide a decimal number. This value can be multiplied by the chosen speed parameter. Typically, 0 corresponds to the joystick being centered, 1 indicates maximum input along that axis, and values in between reflect partial input or diagonal movement.

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 retrieve documents in ElasticSearch based on field values containing or including specific values

I am attempting to retrieve documents from elastic search based on fields that include or contain dynamic text. For example: Here are some sample documents retrieved from elastic { id: 12345, name: test66, description: 'some desc231431', entity_i ...

Creating a "Expand All" feature for Bootstrap UI accordion to easily display all content

Currently, I am utilizing the uib-accordion directive and I aim to include a button that can expand or close all elements within the accordion. Here is the code snippet I have written: <uib-accordion close-others="false"> <div align="right"&g ...

Numerous JQuery AJAX form submissions leading to individual outcomes

I have implemented a script on my page that handles form submissions for multiple forms by calling a specific action. Here is the script: $(function () { $('form').submit(function () { if ($(this).valid()) { $.ajax({ ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Display a particular div upon clicking a specific link, while concealing the other divs

As a beginner in the world of jQuery and coding, I'm encountering some difficulties that I need help with. My goal is to have the 'Vlogging' link activated and show 'Details 1' when the page loads. Then, upon clicking on either &a ...

Using Three.js to rotate a sphere (globe) to a different location (city) on the sphere's surface

Currently, I am in the process of creating a spherical globe with predefined locations that are geo-mapped and represented as points. My goal is to highlight these locations by smoothly rotating the globe along its y-axis from one point to another. Despite ...

The login button has dual functionality, redirecting users to different pages based on their login status. First-time logins will be directed to an agreement page, while returning users will be

During my testing of login functionality, I follow these steps: Enter username Enter password Click on the login button Verify if the agreement page is displayed This is how my Page Object Model (POM) for the login page looks like: class loginPage { ...

VueJS: Even when disabled, clicking a button can still navigate to a different

Is there a way to prevent the button from being clickable when the current page is the first page? Although the button disables as expected, I'm still encountering an issue where the route changes when it's clicked. Code Snippet (Javascript) ...

What is the best way to retrieve an array element from outside a function?

Is there a way to access the distance and pos elements outside of the function in this code snippet? navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longit ...

Linking Java objects with Node.js variables

In this snippet of code, I am utilizing the 'java' module in node.js to create Java objects. Specifically, I am creating four Java objects and aiming to consolidate them as a single object by using the variable 'args' to store these Jav ...

What is the reason behind my page being redirected by an alert?

What could be causing the page to redirect to its PHP script every time an alert is added to my AJAX form, but not redirect when the alert is removed? I want to prevent the page from redirecting to the PHP script. $(document).ready(function(){ ...

Preserve the iframe src value in the dropdown menu even after the page is refreshed

I am trying to figure out how to prevent the iframe src from changing when I refresh the page, unless the user manually changes it using the dropdown menu with JavaScript. Can someone help me with this? <div class="row"> <div class="span9"> ...

Adjust the transparency of an image within an overlay when clicked on the overlay

Having an overlay on a Google map with two images contained within it, I am looking to adjust the opacity of the images when a user clicks on the overlay or on top of an image within the overlay. I attempted to utilize domlistener, but it did not yield the ...

React-select: The default values will only be updated if they are initially set statically

Need help displaying a list of interests from backend data: profile : { interest: ["interest1", "interest2"], }; This is my implementation: import Creatable from "react-select/creatable"; class EditProfileInSettings exten ...

Can AR.js be used to implement extended tracking in Augmented Reality on the web?

Currently, I am working on a web-based project using THREE.js and AR.js for augmented reality. One issue I have encountered is that when the "marker" moves out of view of my camera, the augmented reality image either disappears or remains stuck on the edg ...

I am working with Vue.js 2.0 and attempting to send an event from a `child component`

I've been working with Vue.js 2.0 and I'm facing an issue trying to emit an event from a child component to the parent component, but unfortunately, it's not functioning as expected. Here is a glimpse of my code: child component: <temp ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Tips for incorporating an unordered list inside a list item

<li class="cate-item"> <button class="cate-label" >item 1 </button> <ul class="sub-categ"> <li> sub item 1</li> <li> sub item 2</li> <li> sub item 3</li ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...

Connecting two sets of data from a mongoDB database using vue.js

Hey there, I'm a newcomer to vue and mongodb. I've set up two collections - one for storing user details and the other for business details. When a business registers through a form, their information is saved in mongodb. Now, I've created a ...