• Advertisement
Sign in to follow this  

Can anyone work out what is wrong with this code?

This topic is 1834 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I am working on and html5 javascript game, and I recently just added keyboard input. The concept is that whenever and arrow key is pressed, it updates the position of the shape in the html5 canvas. I thought it was working fine, however after testing, the shapes seem to have some velocity to them, when you hold down the arrow key they seem to pick up speed. I am still new to game development, so it may just be a stupid mistake on my part. Here is the code:



<!DOCTYPE html>
<title>Making things move</title>
<meta charset="utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style type="text/css">
border: 2px solid gray;
background-color: black;
<script type="text/javascript">
$(document).ready(function() {
var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
var x = 0;
var y = 0;
var xWidth = 30;
var yHeight = 30;
function MoveLeft(){
x -= 1;
function MoveUp(){
y -= 1;
function MoveRight(){
x += 1;
function MoveDown(){
y += 1;
function GameLoop(){
window.addEventListener('keydown', function(event) {
  switch (event.keyCode) {
  case 37: 
    case 38: 
    case 39: 
    case 40: 
}, false);
if(x + xWidth >= canvasWidth){
x = canvasWidth - xWidth;
}else if(x <= 0){
x = 0;
if(y + yHeight >= canvasHeight){
y = canvasHeight - yHeight;
}else if(y <= 0){
y = 0;
context.clearRect(0, 0, canvasWidth, canvasHeight);
context.fillStyle="rgb(238, 64, 0)";
context.fillRect(x, y, xWidth, yHeight);
setTimeout(GameLoop, 33);
<canvas id="myCanvas" width="800" height="500">
<!-- Insert fallback content here -->
Just to further explain what is going on, the game loop is running every 33 milliseconds and when it does that it clears the entire canvas and then draws a new one based on the x and y variables which increase or decrease based on the keyboard input.

Share this post

Link to post
Share on other sites
If I read this correctly, you add a new key handler every frame. This means that after 3 frames, you'll handle every key press 3 times.

I think this was the problem, thank you very much!

Share this post

Link to post
Share on other sites

you can also do your boundaries inside your movement functions with if statements. 



if (y+1 < canvasHeight()  {y+=1;}


It will take out several unnecessary lines of code. :P

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement