JavaScript not executing script when key is pressed

Currently, I am learning JavaScript and facing an issue. The spaceship in my game is not moving despite no error being present. Pressing the key w on my keyboard does not trigger any action. I suspect that the problem lies within the line

"document.onekeydown =function(e) {"
, but I am unsure of the exact issue.

let KEY_SPACE = false;
let KEY_W = false;
let KEY_S = false;
let canvas;
let ctx;
let backgroundImage = new Image();

let spaceship = {
  x: 50,
  y: 200,
  width: 100,
  height: 100,
  src: 'img/spaceship.png'
};
let rock = {
  x: 100,
  y: 200,
  width: 200,
  height: 80,
  src: 'img/rock.png'
};


document.onekeydown = function(e) {
  console.log(e.keyCode);
  if (e.keyCode == 32) {
    KEY_SPACE = true;
  }
  if (e.keyCode == 87) { ** THE ISSUE MIGHT BE HERE... **
      KEY_W = true;
  }
  if (e.keyCode == 83) {
    KEY_S = true;
  }
};
document.onekeyup = function(e) {
  console.log(e.keyCode);
  if (e.keyCode == 32) {
    KEY_SPACE = false;
  }
  if (e.keyCode == 87) {
    KEY_W = false;
  }
  if (e.keyCode == 83) {
    KEY_S = false;
  }
};

function startgame() {
  canvas = document.getElementById('canvas');
  ctx = canvas.getContext('2d');
  loadImages();
  draw();
  setInterval(function update() {
    if (KEY_W) {
      spaceship.y -= 1;
    }

    if (KEY_S) {
      spaceship.y = 1;
    }
    console.log("Hi");
  }, 1000);



}

function loadImages() {
  backgroundImage.src = 'img/bg.png';
  spaceship.img = new Image();
  spaceship.img.src = spaceship.src;
  rock.img = new Image();
  rock.img.src = rock.src;
}

function draw() {
  requestAnimationFrame(draw);
  ctx.drawImage(backgroundImage, -100, 0, 874, 562);
  ctx.drawImage(spaceship.img, spaceship.x, spaceship.y, spaceship.width, spaceship.height);
}
canvas {
  background-color: darkgrey;
}
<body onload="startgame()">
  <canvas id="canvas" width=" 720" height="480"></canvas>
</body>

Answer №1

Initially, it appears that the function onekeydown() is missing but you may have meant onkeydown() instead. Additionally, only checking for key inputs every second can lead to missed inputs or input delays. It would be more effective to directly modify the spaceship's value within the onkeydown() and onkeyup() functions.

Answer №2

Hey there! Check out what @Oscar Umhin suggested:

let KEY_SPACE = false;
let KEY_W = false;
let KEY_S = false;
let canvas;
let ctx;
let backgroundImage = new Image();

let spaceship = {
  x: 50,
  y: 200,
  width: 100,
  height: 100,
  src: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSknVdXFn_hKNZqIkhf2n2mJ7seozp3S3pzJwQSFPJHCKVrgkEMJ1QOR8CLCSrOXbdGpE0&usqp=CAU'
};
let rock = {
  x: 100,
  y: 200,
  width: 200,
  height: 80,
  src: 'https://img.favpng.com/18/3/2/asteroid-space-rock-outer-space-comet-png-favpng-xTh5n6HtQqakzdAebMJ4Tn5Eb_t.jpg'
};


document.onkeydown = function(e) {
  console.log(e.keyCode);
  if (e.keyCode == 32) {
    KEY_SPACE = true;
  }
  if (e.keyCode == 87) {
      KEY_W = true;
  }
  if (e.keyCode == 83) {
    KEY_S = true;
  }
  update();
};
document.onkeyup = function(e) {
  console.log(e.keyCode);
  if (e.keyCode == 32) {
    KEY_SPACE = false;
  }
  if (e.keyCode == 87) {
    KEY_W = false;
  }
  if (e.keyCode == 83) {
    KEY_S = false;
  }
};

function startgame() {
  canvas = document.getElementById('canvas');
  ctx = canvas.getContext('2d');
  loadImages();
  draw();
}
function update() {
    if (KEY_W) {
      spaceship.y -= 1;
    }

    if (KEY_S) {
      spaceship.y = 1;
    }
    console.log("Hi");
  }
  
function loadImages() {
  backgroundImage.src = 'https://orsted.com/-/media/WWW/Images/Corp/Campaign/SpaceSafari/space-safari-background.png';
  spaceship.img = new Image();
  spaceship.img.src = spaceship.src;
  rock.img = new Image();
  rock.img.src = rock.src;
}

function draw() {
  requestAnimationFrame(draw);
  ctx.drawImage(backgroundImage, -100, 0, 874, 562);
  ctx.drawImage(spaceship.img, spaceship.x, spaceship.y, spaceship.width, spaceship.height);
}
canvas {
  background-color: darkgrey;
}
<body onload="startgame()">
  <canvas id="canvas" width=" 720" height="480"></canvas>
</body>

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

Interactive paper API featuring a convenient close button

I am currently working with the Paper component from Material UI, which you can find here: https://mui.com/components/paper/ Below is the code I have implemented so far: <Paper className="modal" elevation={3}> {..Content..} </Paper& ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

How can I add animation to an HTML5 video using jQuery?

How can we add animation to an HTML5 video element? <div id="cont"> <video id="movie" width="320" height="240" preload controls> <source src="pr6.ogv" type='video/ogg; codecs="theora, vorbis"'> <source src="p ...

To manipulate the array in a more complex manner, either add or remove the item based on its existence: if it's already in the array, remove it; if it

As I prepare to send key-value pairs to the backend in the form of a JSON structure, each representing a category (e.g., customer churn rate), I encounter an issue. The idea is to add checkmarked options to the array of their respective categories. However ...

Generating dynamic input field values using jQuery in a CodeIgniter PHP framework application

I am facing an issue where I am unable to display the value from a dynamically created input field in the page controller. Below is the jQuery code used to append the dynamic input fields: var tableRow='<tr>'; tableRow+=' ...

Python code to locate images within HTML source code

Searching for images in an html source code can be tricky. I prefer using regex over the html.parser method, but I'm open to learning if you can explain it simply like you would to a child. I wish I could use beautifulsoup, but mastering the hard way ...

Troubleshooting Nested jQuery Plugin Selector Problems

I'm looking to have the ability to nest one plugin inside another. However, my selectors seem too broad and are capturing elements within the nested plugin as well. For instance, consider the following HTML structure: <div class="my-plugin"> ...

Rearrange the characters within the variable before inserting them after

I'm currently dealing with an external system that generates outdated code, however, I do have access to css and javascript. The specific issue at hand involves working with a table that displays each item on a separate row, sometimes resulting in up ...

Having trouble retrieving my static files in express.js - running into conflicts

Hey there! I'm currently working on creating a webapp for purchasing tickets using express.js. I've encountered an issue with loading static files onto a specific page that directs users to information about a party. It seems like express.js is u ...

Dynamic element not firing jQuery event

My question is...https://i.sstatic.net/me2uQ.png // Using ajax to dynamically create a table $(".n").click(function(){ var id= $(this).closest('tr').find('td.ide2').html(); //for displaying the table $.ajax({ ...

Having trouble adding a button to a GridLayout in my NativeScript application

My attempt to use a Button alongside some Images in a single row within a GridLayout resulted in the Button covering the entire row along with the images. Here is the HTML code I used: <GridLayout columns="4*,*,*,*,*,*" rows="*"> <Button text ...

AngularJS single page applications experiencing issues with loading scripts and stylesheets upon page reload

Homepage Setup : <ng-view></ng-view> Angular Routing Configuration : when('/', { url: '/', templateUrl: 'site/home', controller: 'indexController' }). when(&apos ...

Implementing validation for multiple email addresses in JavaScript: A step-by-step guide

Currently, I am utilizing Javascript to perform validation on my webpage. Specifically, I have successfully implemented email validation according to standard email format rules. However, I am now seeking assistance in enhancing the validation to allow for ...

Is it possible to use a JavaScript string as a selector in jQuery?

So, my issue is with the following JavaScript code snippet: for ( i=0; i < parseInt(ids); i++){ var vst = '#'+String(img_arr[i]); var dst = '#'+String(div_arr[i]); } I'm wondering how I can proceed in jQuery to handle ...

Understanding the relationship between Ajax callbacks and variable scope while importing JSON data into an array

I am using ajax to load a geoJSON file with the goal of pushing the coordinates of a MultiPoint feature into a global array for later use. I am encountering an issue with my callback function in the given code snippet. The intention here is to read the da ...

Arranging div elements into columns side by side with Flexbox

I've been working on the frontend of my chat web app and recently discovered flexbox. I'm struggling to center two elements with a blue background below the "CHAT" heading, aligned with two green elements like a black square. My challenge lies in ...

Utilizing the "Skip navigation" functionality in conjunction with the Durandal router

Currently, I am developing a HTML5 single page application that must adhere to the "WCAG 2.0" guidelines. In this project, I am utilizing Twitter Bootstrap as the frontend framework and Durandal.js for the SPA functionality. I am seeking advice on the be ...

Setting form input values to a new value in Angular 8

Is it possible to reset the value of a form input and then set another value from a service? I would like to store the old value in saveService, reset the service, and change the name attribute of the service to Hello World! Even though I correctly have t ...

Creating a form that seamlessly integrates with the content using a combination

As I continue to explore the depths of WordPress and delve into learning HTML/CSS, my latest project involves embedding an email signup form on my website using Klaviyo. The basic code provided by their form creator initially had everything condensed into ...

Utilizing Parameters in Route Mapping within Node.js API

Currently, I am in the process of setting up an API for my website. However, I am encountering some difficulties with the route params. At the moment, I have implemented two routes: const route1 = require('./routes/route1') const route2 = requir ...