i.e. I'm looking to get two circles to be moved around simultaneously. One controlled by the arrow keys and the other with WASD.
Right now when I push "W", I can't push "up" at the same time to get it working where both circles move up at the same time, just the circle controlled by "W" moves up.
Essentially only one key can be pressed and captured at a time and I want multiple keys to be captured at once.
This is my code maybe you can tell me where I went wrong:
<body>
<section>
<div>
<canvas id="canvas" width="300" height="200">
</canvas>
</div>
<script type= "text/javascript">
var canvas;
var ctx;
var dx = 5;
var dy = 5;
var x = 150;
var y = 100;
var x2 = 250
var y2 = 150
var WIDTH = 300;
var HEIGHT = 200;
function circle(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.fill();
}
function circle2(x, y, r) {
ctx.beginPath();
ctx.arc(x2, y2, r, 0, Math.PI * 2, true);
ctx.fill();
}
// The beginPath makes sure we start a new path, the arc allows us to define the shape and size of the circle (x, y, radius, start angle, end angle, anticounter clockwise) ,
function rect(x, y, w, h) {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.closePath();
ctx.fill();
ctx.stroke();
} // draw a rectangle the same size as the canvas
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
} // clears the rectangle this made inside the canvas
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d"); // sets drawing contex (2d) has built in functions (getContext function 2d means somethingto it
return setInterval(draw, 10); // draws the screen every 10 milliseconds
}
function doKeyDown(evt) {
switch (evt.keyCode) {
case 38: /* Up arrow was pressed */
if (y - dy > 0) {
y -= dy;
}
break;
case 40: /* Down arrow was pressed */
if (y + dy < HEIGHT) {
y += dy;
}
break;
case 37: /* Left arrow was pressed */
if (x - dx > 0) {
x -= dx;
}
break;
case 39: /* Right arrow was pressed */
if (x + dx < WIDTH) {
x += dx;
}
break;
// First Circle Above
case 87: /* Up arrow was pressed */
if (y2 - dy > 0) {
y2 -= dy;
}
break;
case 83: /* Down arrow was pressed */
if (y2 + dy < HEIGHT) {
y2 += dy;
}
break;
case 65: /* Left arrow was pressed */
if (x2 - dx > 0) {
x2 -= dx;
}
break;
case 68: /* Right arrow was pressed */
if (x2 + dx < WIDTH) {
x2 += dx;
}
break;
}
}
// what each case is saying for example the first one is if the y postion -5 is less than zero it can't move (sets a boundary) and y is equal to itself - 5 when a key is pressed which changes its postion by 5 everytime a key is pressed
function draw() {
clear();
ctx.fillStyle = "white";
ctx.strokeStyle = "black";
rect(0, 0, WIDTH, HEIGHT);
ctx.fillStyle = "purple";
circle(x, y, 10);
ctx.fillStyle = "green"
circle2(x2, y2, 10);
}
init();
window.addEventListener('keydown', doKeyDown, true)
// checks for event (type, listener , usecapture)
</script>
</section>
</body>