The Keydown event in Three.js should initially move my player a set distance, however, the further the player moves

I've been working on a Threejs project where I have set up keydown controls for my player character in the animate function. Pressing 'a' and 'd' moves the character left and right, while 'w' and 's' move them up and down.

One issue I've encountered is that when I hold down one of the keys, the character's movement distance increases over time. This causes the character to jump farther after releasing and pressing the key again, eventually resulting in them jumping across the entire screen with just one press.

Below is a snippet of the code:

   $(document).keydown(function(e){
        if (e.keyCode == 87) {
            player.position.y += 0.05;
        }
        if (e.keyCode == 83) {
            player.position.y -= 0.05;
        }
        if (e.keyCode == 65) {
            player.position.x -= 0.05;
        }
        if (e.keyCode == 68) {
            player.position.x += 0.05;
        }
   });

I would really appreciate some assistance with this. Thank you! :)

Answer №1

In my opinion, it would be more efficient to transfer the logic to the render loop in the following manner

When outside the render loop:

$(document).keydown(function(e){
    if (e.keyCode == 87) {
        movementY = +0.05;
    }
    if (e.keyCode == 83) {
        movementY = 0.05;
    }
    if (e.keyCode == 65) {
        movementX = -0.05;
    }
    if (e.keyCode == 68) {
        movementX = 0.05;
    }
});

$(document).keyup(function(e){
    movementX = 0;
    movementY = 0;
});

When inside the render loop:

player.position.x += movementX;
player.position.y += movementY;

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

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...

"Exploring the possibilities of Sketchfab through an AJAX JSON

Currently, I am on a quest to gather the URL for the thumbnail of a Sketchfab model. To access this information, you can visit: Upon visiting the above URL, all the necessary details are visible to me. My next step involves making an AJAX call to dynami ...

Unable to load routes from ./app.js in the file ./src/routes/index.js

Just dipping my toes into the world of nodejs. I recently moved all my routes from app.js to a separate file located at PROJECT_DIR/src/routes/index.js. However, when I try to open the page in my browser, it displays "Cannot GET /wines". Below are snippets ...

Encountering a problem in React when trying to install a color detection library

Hey there, I'm working on a Spotify-clone project where I want to detect the dominant color of an image and use it as the background color. Unfortunately, I've run into some errors while trying to integrate libraries like color-theif, node-vibran ...

Execute an xmlhttprequest and then redirect to a different URL

I'm a beginner when it comes to AJAX and JavaScript. My goal is to first show a confirmation box, then send an XMLHttpRequest if confirmed. After that, I want to redirect the user to a new page. Below is my current code: <script type="text/javascr ...

Laravel's routing system may cause complications when trying to send data via jQuery AJAX post requests

My current challenge involves passing an ID to a PHP script through AJAX. Previously, everything was working perfectly with the code snippet below: var baseURL = '/W4W/public/'; function voteUp(){ var snippetID = document.getElementById(&ap ...

JavaScript featuring Ajax functionality

Although I have limited experience in web programming, I am currently testing a simple add-on to integrate with my app. The webpage I have created displays multiple rows, each containing an editable field for user input. After the user inputs data into th ...

Using Ajax for updating table content on a JSP webpage section

I am working on implementing Ajax functionality for a table to enable partial updates every hour. Below is a snippet of my JSP code: < head > < meta http - equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < titl ...

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

How can AJAX be utilized to show search results dynamically?

At the moment, I have a PHP page that pulls a list of results from my SQL database and displays the ID and names. There is a search bar at the top where you can search for keywords in the "name" field, and when you click on search, it takes you to a new p ...

Applying style changes to the height on scroll event in Javascript for Chrome, Firefox, and Internet Explorer

I am working on triggering an event when scrolling to a specific height. I have code that successfully adds a style in Chrome, but it is not functioning properly in IE. Can anyone provide assistance? myID = document.getElementById("subnav"); var mySc ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

Switching between numerical and alphabetical input using JQuery

How can I switch between allowing character and numeric input in a textbox? I currently have a JQuery function that restricts input to numbers only $('.numeric').on('input', function (event) { this.value = this.value.replace(/[^0 ...

Is it possible for jQuery AJAX to function correctly on mobile Safari, but encounter issues when used on a

I'm encountering an issue with a basic jQuery ajax function that logs the user in through a UIWebView. Strangely, it returns blank only when used in a UIWebView, as it works perfectly in mobile Safari, Chrome, and Firefox on my computer. Below is the ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

I am currently working on determining whether a given string is a palindrome or not

I'm currently working on a function that checks whether a given string is a palindrome. So far, my tests are passing except for the following cases: (_eye, almostomla, My age is 0, 0 si ega ym.) This is the function I've implemented: function pa ...

Set a variable equal to the output of an external function, but receive an undefined value in

I've been facing an issue where I'm trying to store the value of an external function in a JavaScript variable, but it keeps returning undefined. The external function in question is designed to search for a specific record within a database: f ...

Find the variance between the sums of columns 3 and 5 using Angular

Is there a method to calculate the variance between column 3 and the last one in a table? <body ng-app="Test"> <section style="margin-top:80px"> <h3>Plastic Calculator Form Version 2.0</h3> <div ng-controller="TestCo ...

Is there a way for me to record the variable's name instead of its linked data?

Currently, I am developing a node.js program that monitors the prices of different currencies. While I can successfully retrieve the prices, I would like the program to also display the names of the currencies along with their prices. In the code snippet b ...

An issue has been encountered in the code during the installation of react.js

node:internal/modules/cjs/loader:1148 throw err; ^ Error: Module 'C:\Users\hp\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js' could not be found. at Module._resolveFilename (node:internal ...