Is there an issue with the proper execution of keypresses/updates in the code

I'm currently stuck while trying to develop a game in Javascript. My challenge lies in detecting keypresses and constantly checking if they are being held down to move the character. Below is the code I have been using:

var THREE;
var keys;
var update;
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer();
var player_fov = 45;
var player_aspect = window.innerWidth / window.innerHeight;
var player_near = 0.1;
var player_far = 10000;
var player_camera = new THREE.PerspectiveCamera(player_fov, player_aspect, player_near, player_far);
var player_material = new THREE.MeshNormalMaterial({color: 0xd0bd4b});
var player_geometry = new THREE.BoxGeometry(1,1,1,1);
var player = new THREE.Mesh(player_geometry, player_material);


function INIT()
{
    scene.add(player);
    player_camera.position.z = 5;
    window.addEventListener('keydown', function (e) {
        keys.keys = (keys.keys || []);
        keys.keys[e.keyCode] = true;
    });
    window.addEventListener('keyup', function (e){
        keys.keys[e.keyCode] = false;
    });
    requestAnimationFrame(INIT);
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    renderer.render(scene, player_camera);
    if(keys.keys && keys.keys[87]) //w
    {
        player.position.y += 1;
    }
    if(keys.keys && keys.keys[65]) //a
    {
        player.position.x -= 1;
    }
    if(keys.keys && keys.keys[83]) //s
    {
        player.position.y -= 1;
    }
    if(keys.keys && keys.keys[68]) //d
    {
        player.position.x += 1;
    }
}

The movement isn't working properly despite pressing different keys. It should be an easy error to identify for experienced programmers. Is there something wrong with my understanding of event listeners or requestAnimationFrame? If so, please provide guidance on how to rectify it. Thank you.

Answer №1

Your code could use some improvements:

  1. Make sure to call the INIT() function for the code to run.
  2. Avoid using requestAnimationFrame in the INIT function as it doesn't need to run every frame.
  3. Create a separate render() function to be called at the end of INIT or right after calling it, and include the requestAnimationFrame(render) inside this new function.
  4. Consider using a javascript Object instead of an array for the keys.

Here is an example of how these changes could look:

var keys = {};
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer();
var player_fov = 45;
var player_aspect = window.innerWidth / window.innerHeight;
var player_near = 0.1;
var player_far = 10000;
var player_camera = new THREE.PerspectiveCamera(player_fov, player_aspect, player_near, player_far);
var player_material = new THREE.MeshNormalMaterial({color: 0xd0bd4b});
var player_geometry = new THREE.BoxGeometry(1,1,1,1);
var player = new THREE.Mesh(player_geometry, player_material);

INIT();

function INIT()
{
  document.addEventListener('keydown', function (e) {
    keys = (keys || {});
    keys[e.keyCode] = true;
  });

  document.addEventListener('keyup', function (e){
    keys[e.keyCode] = false;
  });
  
    scene.add(player);
    player_camera.position.z = 5;
  
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
  
   render();
}


function render(){
    requestAnimationFrame(render);

    if(keys && keys[87]) //w
    {
      player.position.y += 0.2;
    }
    if(keys && keys[65]) //a
    {
      player.position.x -= 0.2;
    }
    if(keys && keys[83]) //s
    {
      player.position.y -= 0.2;
    }
    if(keys && keys[68]) //d
    {
      player.position.x += 0.2;
    }
    renderer.render(scene, player_camera);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.min.js"></script>

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 are involved in setting up a local server on my computer in order to create an API that can process http requests from Flutter?

New to API creation here, so please be patient. I plan to eventually host my API on a more robust server, but for now, I want to get started by setting something up locally on my PC to work on backend functions. The API goals include: Verify incoming requ ...

Create a series of vertical lines using jQuery

I'm dealing with a JSON data set that I want to use to generate a grid. In addition to the grid, I also need to display vertical lines above it based on certain values: var arr = []; arr= [ {"Measure":"Air Pollution","Rank":"1","Value":"15.5"}, ...

What is the best way to receive several responses from a PHP file using AJAX?

My PHP file is handling 2 operations: 1. Submitting data from a form into a database table, and 2. Sending an email. I am looking to display status messages through ajax. For instance, showing "First operation done, please wait for the second" and then di ...

Polymer: Basic data binding is not functional in the second element

After dedicating 6 hours to this problem, I still can't seem to find a solution. Below is the code snippet from index.html: <flat-data-array availableModes="{{modes}}" id="dataArray"></flat-data-array> <flat-strip-view availableModes=" ...

Ajax loaded scripts are unable to access global variables

Index.html <script> let bar = 1; </script> This html page is being loaded multiple times on the page using AJAX: article.html <script> if (bar === 1) { // perform a task } // Error: bar is not defined </script> Bar is a simple ...

When navigating within a page, Firefox shows {{ }} tags while Chrome does not in AngularJS

After experimenting with various techniques, I managed to successfully hide the content section upon initial page load. However, when navigating within the page, the tags still appear. Any suggestions on how to resolve this issue? You can view the proble ...

What is the best way to add a checkbox tag in Rails using JavaScript?

I am attempting to use javascript to append the values from option fields to checkboxes in Rails. Here is a snippet of my javascript code: $("#regions option").each(function(){ $("#region-checkboxes").append('<li><%= check_box_tag "region ...

two collided collada entities

Having trouble using Ray intersect to check for collisions between two collada objects. No luck so far :( Here is my code: http://jsfiddle.net/XqQzF/ object.updateMatrix(); // ray var f_vector = new THREE.Vector3( 0, 0, -1 ); ...

The most effective method for incorporating a header and footer into an HTML page utilizing a variety of client-side frameworks

Looking for a solution for my HTML project where I want to incorporate a header and footer to minimize rework. Any suggestions on a good approach? I have experimented with AngularJS using ng-include, and here is the code snippet: var app = angular.module ...

In TypeScript, both 'module' and 'define' are nowhere to be found

When I transpile my TypeScript using "-m umd" for a project that includes server, client, and shared code, I encounter an issue where the client-side code does not work in the browser. Strangely, no errors are displayed in the browser console, and breakpoi ...

How to continuously stream and display an actively updating log text file from a server in real-time onto a web textbox, eliminating the need for webpage

There is a log file in notepad format with values like this: 11.23445646,56.3456578954, 10.23445646,26.3456578954, and 16.23445646,-46.3456578954. I want to retrieve the data from the server and display it in a website textbox. The first value, which is ma ...

What is the best way to secure videos and other static files with authentication in a next.js web application?

My goal is to provide static content, specifically videos, exclusively to authorized visitors. I want to secure routes so that they are only accessible to authenticated users. However, the challenge arises when trying to display a video on a page located i ...

Searching recursively for keys with empty values in an array using Javascript

I've written a function that recursively locates empty values in a nested array. The function initially produces the correct value, but it seems to reset it to the input value before returning the result. What could I be overlooking? Below is my co ...

Vue.js will trigger the updated() method only when a particular array undergoes changes

Working on a chat feature and looking for a way to automatically scroll to the end of the conversation when new messages are added. The current solution involving the updated() function works well, but there's a complication with a vue-timepicker com ...

Checking for the status of a checked box when the ::after pseudo-element is added after the box is marked

I need help verifying if a checkbox is checked in my selenium code. After the checkbox is checked, it adds ::after but I'm struggling to confirm the existence of that pseudo element. Can anyone assist me in resolving this issue? I have been unable to ...

navigating through an array with a loop (for)

I created a basic phone book program where users can input a name and it will search an array of objects for the corresponding phone number. If the name is found, it will display the name and phone number. However, I am facing an issue where even though ...

Having Trouble Redirecting to Another Page from My Ionic Framework Controller?

Struggling to figure out why my app isn't switching to another page when clicking in my controller. Any help or pointers on what I might be missing or doing wrong would be greatly appreciated! Here's the code snippet from my app.js file: $s ...

Guide on utilizing the disable feature in SortableJS for a Vue project

I have successfully implemented the draggable effect on my el table using element-ui-el-table-draggable and it's working perfectly. Now, I am looking to incorporate the disable option from SortableJS, but I'm unsure how to integrate these two fu ...

Tips for leveraging async and await within actions on google and API integration

Currently, I am developing an Actions on Google project that utilizes an API. To handle the API calls, I am using request promise for implementation. Upon testing the API call, I observed that it takes approximately 0.5 seconds to retrieve the data. Theref ...

What's with the lack of acknowledgment when I triumph in rock, paper, scissors, lizard, spock?

My game is running smoothly, except for when lizard or spock are involved and I win. For some reason, the outcome does not display correctly, even though it works fine when I lose. I've double-checked for typos but couldn't find any. If someone c ...