Javascript initial keypress delay for movement in 3D space

I am aiming for a seamless movement experience when pressing a key - with the object initiating its movement upon the first press and then continuously moving while the button is held down.


//setting movement speeds
var xSpeed = 0.5;
var zSpeed = 0.5;

document.addEventListener("keydown", onDocumentKeyDown, false);

function onDocumentKeyDown(event) {
  var keyCode = event.which;
  if (keyCode == 87) {  //W KEY
    car.position.z -= zSpeed;
  } else if (keyCode == 83) {  //S KEY
    car.position.z += zSpeed;
  } else if (keyCode == 65) {  //A KEY
    car.position.x -= xSpeed;
  } else if (keyCode == 68) {  //D KEY
    car.position.x += xSpeed;
  } else if (keyCode == 32) {
    car.position.set(0, 0, 0);
  }
};

My goal is to smoothly control a GLTF imported model on a plane using keyboard inputs. I attempted to wrap the program in a loop and make the keyboard state available within that loop's scope but unfortunately ran into issues.

Answer №1

One way to approach this scenario is by adjusting the velocity based on keyup/keydown events, with the loop updating the car's position accordingly.

// set initial movement speeds
var xSpeed = 0;
var zSpeed = 0;

document.addEventListener("keydown", onDocumentKeyDown, false);
document.addEventListener("keydown", onDocumentKeyUp, false);

function onDocumentKeyDown(event) {
  var keyCode = event.which;
  if (keyCode == 87) {  //W KEY
    zSpeed = -0.5;
  } ... // repeat for other keys
};


function onDocumentKeyUp(event) {
  var keyCode = event.which;
  if (keyCode == 87) {  //W KEY
    zSpeed = 0;
  } ... // repeat for other keys
};

function loop() {
car.position.z += zSpeed;
car.position.x += xSpeed;
window.requestAnimationFrame(loop);
}

If you prefer smoother acceleration and deceleration, you can adjust an acceleration factor in response to key events, with the loop managing the velocity changes.

For further exploration of simulating real-world concepts through code, check out Daniel Shiffman's insightful article:

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

Customizing the appearance of React Navigation StackNavigator through background color changes and styling

Recently delving into React Native, I've managed to create a basic app with three different scenes. Initially, I used Navigator for navigation purposes, but found it to be sluggish and decided to give React Navigation (found at https://reactnavigation ...

Using `ngRepeat` on a different array of values for repetition

Working with AngularJS. Here is an example of a JSON object: "skills": { "Charisma": {}, "Dexterity": { "Sk3": [ [ true, true, true, true, false ], 44 ] }, ... And the corresponding HTML: <div class="pan ...

Tips on leaving comments inside a render <div>

Hey there! I'm facing an unusual issue in my React+Webpack project. Even though I marked a line as a comment using //, it still gets rendered in the HTML output. Strangely, I have never encountered this problem before and can't figure out what tr ...

Currently seeking user coordinates for Vue implementation

I recently started using Vue and I'm working on capturing the lat/long of a user to be used in other functions within Vue. Currently, I am retrieving the coordinates and plan to utilize them in an API but for now, I am just logging them. Although I c ...

What is the best way to dynamically load a local image in a React component by using the file path stored in an object attribute

How can I load an image stored locally? export const dataJeuxGrosLot = [ { id: 1, title: 'Jeu Spécial Noel', price: '$59.99', prize: '$3000.99', startDate: new Date(2023, 2, 20, 15, 30, 12), // (yyyy, mm, ...

leveraging AJAX to showcase information retrieved from a MySQL database

Hello! I am brand new to PHP and have little knowledge of AJAX. I am in the process of creating a photo gallery site and have used the following code to display my photos. I would like to make it possible, using AJAX or any other language, for someone to c ...

Efficiently and consistently refreshing the DOM with information while maintaining page integrity

I'm currently developing a Single Page Application (SPA) that utilizes AJAX to dynamically load content into a specific div. The layout consists of a side accordion menu, where clicking on an item loads relevant information in a neighboring div. Howev ...

When navigating using the next and back buttons, the active state in Angular is automatically removed

Looking for some assistance with my quiz app setup. Each question has True/False statements with corresponding buttons to select T or F. However, when I click the next/back button, the active class is not being removed from the previous selection. As a beg ...

Can one determine if a webpage is being displayed within an Infragistics igDialog?

Occasionally, my web page is displayed without a container and other times it's embedded within an igDialog of another container page, based on the user's navigation throughout our web application. Is there a way, using pure javascript or jQuery ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

The power of Ionic 2 combined with the Web Audio API

I am currently developing an Ionic 2 application that requires access to the user's microphone. When working on a web platform, I would typically use the following code snippet to obtain microphone access. navigator.getUserMedia = (navigator['ge ...

Ajax: The function assigned to the route does not get executed

Pressing a button triggers a confirmation box. If 'ok' is clicked, the div called 'EventData' should display the word 'reached'. The confirmation box appears when the button is clicked, but 'EventData' does not show ...

How to make text dynamically shrink with TailwindCSS class 'flex-shrink-0'

I've designed an 'Album' (React) component to showcase album artwork, name, and release date in a card-like format. This component consists of two divs - one for the photo and the other for text. Each artist's discography displays multi ...

Setting up jade includes with gulp-jade: A comprehensive guide

Struggling with setting up Jade includes in your gulpfile.js while using gulp-jade? Check out this link for more information. Below is a snippet from the gulpfile.js: var gulp = require('gulp'); var browserSync = require('browser-s ...

JavaScript stylesheet library

What is the top choice for an open-source JavaScript CSS framework to use? ...

What would be the ideal technology stack (modules, frameworks) to use for delving into node.js and creating a successful first project that allows for learning and growth?

A year ago, I took my first small steps into the world of Node.js. Back then, I was overwhelmed by the sheer number of modules and frameworks available. Now, I am determined to dive deeper into the Node environment and kickstart a web-based project that wi ...

Transform the hue of symbols within D3-legend

I am attempting to modify the appearance of symbols in a legend. The variable below represents the available symbol types: var symbolTypes = { "triangleUp": d3.svg.symbol().type("triangle-up"), "circle": d3.svg.symbol().type("circle") }; I use this varia ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

Guide for ordering a query by the most recent updatedAt within a nested one to many relationship

I'm dealing with a set of interconnected entities structured as follows: Entity1 -> Entity2 -> Entity3 (illustrating one-to-many relationships with arrows) I am utilizing MikroORM for this purpose. Is there a way to construct a findAndCount q ...

I possess a webpage containing a div element that is loaded dynamically through ajax

One issue I'm facing is with a page containing a div that gets loaded via ajax when a button is clicked. The problem arises when a user tries to refresh the page by pressing F5, as the content of the div gets lost! Is there a way to ensure that when ...