-1
const WIDTH = 640;
const HEIGHT = 480;
const PLAYER_SIZE = 20;
const REPAINT_DELAY = 50;
const EASY_DELAY = 1750;
const MODERATE_DELAY = 1000;
const HARD_DELAY = 750;
const MAX_BLOCKS = 100;


var context;
var DX;
var DY;

DX and DY are the position of the blue square. What I'm trying to accomplish is that when using the arrow keys I am moving the Position of the blue square.

var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;


window.onload = init;

function init()
{
  canvas = document.getElementById("myCanvas");
  context = canvas.getContext("2d");
  context.fillStyle = "#0000FF";
  DX = WIDTH / 2 - PLAYER_SIZE / 2;
  DY = HEIGHT / 2 - PLAYER_SIZE / 2;
  setInterval('draw()', 25)
}

function clearCanvas()
{
  context.clearRect(0,0,WIDTH,HEIGHT);  
}

function draw()
{
  clearCanvas();
  if (rightKey) DX += 5;
  else if (leftKey) DX -= 5;
  if (upKey) DY -= 5;
  else if (downKey) DY += 5;
  if (DX <= 0) DX = 0;
  if ((DX + DY) >= WIDTH) DX = WIDTH - DY;
  if (DY <= 0) DY = 0;
  if ((DY + DX) >= HEIGHT) DY = HEIGHT - DX;
  context.fillRect(DX, DY, PLAYER_SIZE, PLAYER_SIZE);
 }

 function onKeyDown(evt) {
   if (evt.keyCode == 39) rightKey = true;
   else if (evt.keyCode == 37) leftKey = true;
   if (evt.keyCode == 38) upKey = true;
   else if (evt.keyCode == 40) downKey = true;
 }

function onKeyUp(evt) {
 if (evt.keyCode == 39) rightKey = false;
 else if (evt.keyCode == 37) leftKey = false;
 if (evt.keyCode == 38) upKey = false;
 else if (evt.keyCode == 40) downKey = false;
}

I think here at the end I'm missing two lines of code that sort of call the two previous functions? That's where I'm getting confused.

This is what I have so far it isn't working for me at the moment. Any help would be appreciated!

SHiRKiT
  • 1,024
  • 3
  • 11
  • 30

1 Answers1

0

The error in your code is this:

setInterval('draw()', 25)

when it should be

setInterval(draw, 25)

setInterval's first argument should be function, now it's a string.

Here's my simple Updated demo with class based moving objects: https://jsfiddle.net/mulperi/oh7n3Lx9/

Also, see here why requestAnimationFrame() is better than setTimeout() or setInterval(): Why is requestAnimationFrame better than setInterval or setTimeout

For keypresses I suggest you make an object that holds boolean values for all keys and then, on the update-functions of different objects like player for example, you just check if the keys it needs are being pressed.

And you don't need to use keyCode anymore, see here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

I hope that helps you!

Here is the full code of my take on moving the player objects around the canvas. It may help you to think about the structure of your code:

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>World's BEstest Game</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body>
    <h1 style="font-family: Comic Sans MS; color: hotpink; text-shadow: 2px 2px 2px pink">2 Player Movement</h1>
    <p>Class based player objects and keyboard controls</p>
    <p>Use the arrow and WASD keys to move your balls</p>
    <canvas id="canvas" style="border:1px solid black; border-radius: 5px;">

    </canvas>
    <script>
      const c = document.getElementById("canvas");
      const ctx = c.getContext("2d");

      let settings = {
        width: 100,
        height: 100,
        speed: 1
      };

      c.width = settings.width;
      c.height = settings.height;

      /*
        Object holding boolean values for every keypress
      */
      let keyPresses = {};

      function listenKeyboard() {
        document.addEventListener("keyup", keyUp);
        document.addEventListener("keydown", keyDown);
      };

      const keyUp = e => {
        keyPresses[e.key] = false;
      };

      const keyDown = e => {
        // console.log(e.key)
        keyPresses[e.key] = true;
      };



      class Player {

        constructor(x, y, color, left, right, up, down, radius) {
          this.x = x;
          this.y = y;
          this.color = color;
          this.left = left;
          this.right = right;
          this.up = up;
          this.down = down;
          this.radius = radius;
        }

        draw() {
          ctx.fillStyle = this.color;
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
          ctx.closePath();
          ctx.fill();
        }

        update() {
          if (keyPresses[this.left]) {
            this.x -= settings.speed;
          }
          if (keyPresses[this.right]) {
            this.x += settings.speed;
          }
          if (keyPresses[this.up]) {
            this.y -= settings.speed;
          }
          if (keyPresses[this.down]) {
            this.y += settings.speed;
          }

                    // Screen bounds
          if (this.x < 0 + this.radius) this.x = 0 + this.radius;
          if (this.y < 0 + this.radius) this.y = 0 + this.radius;
          if (this.x > settings.width - this.radius) this.x = settings.width - this.radius;
          if (this.y > settings.height - this.radius) this.y = settings.width - this.radius;
        }

      }

      /*
          Creating the player objects
      */
      let p1 = new Player(25, 25, "red", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", 10);
      let p2 = new Player(75, 75, "black", "a", "d", "w", "s", 5);

      function draw() {
        ctx.clearRect(0, 0, settings.width, settings.height);
        p1.draw();
        p2.draw();
      };

      function update() {
        draw();
        listenKeyboard();
        p1.update();
        p2.update();
        requestAnimationFrame(update);
      };

      requestAnimationFrame(update);

    </script>
  </body>

</html>
Mulperi
  • 1,450
  • 1
  • 14
  • 24