UPDATE:
It seems that you are working on a "pong" or "breakout" game, so I decided to try my hand at creating an HTML canvas version for fun. Here's a simple implementation that demonstrates:
- Drawing two paddles on a canvas (original author)
- Keeping track of the paddle 'boxes' in an array (original author)
- Using a loop with
setInterval
to redraw the canvas as updates are made (original author)
- Allowing keyboard input to move shapes around on the HTML canvas (my contribution)
Check out the fiddle for a working demo and the full code: http://jsfiddle.net/z4ckpcLc/1/
I'm not sharing the complete code because most of it isn't mine. I borrowed the box drawing and tracking from this site:
The new function I added is the arrowKeyMove()
handler, connected to the onkeydown
event of document.body
like so:
document.body.onkeydown = arrowKeyMove;
function arrowKeyMove(e) {
var direction = 0; // -1 for left, 1 for right, 0 for no movement
var moveFactor = 10; // higher factor means more movement when arrow keys are pressed
var arrowKeyUsed = false; // indicates which paddle is being moved
switch (e.which) {
case 37:
// left arrow (upper paddle)
direction = -1;
arrowKeyUsed = true;
break;
case 39:
// right arrow (upper paddle)
direction = 1;
arrowKeyUsed = true;
break;
case 65:
// Key "a" for left strafe (lower paddle)
direction = -1;
break;
case 68:
// Key "d" for right strafe (lower paddle)
direction = 1;
break;
}
var boxIndex = 1; // default to lower paddle
if (arrowKeyUsed) { // moving upper paddle with arrow keys
boxIndex = 0;
}
var maxX = 240; // constrain movement within 10px of box borders (240 == canvas width minus paddle width minus padding)
var minX = 20;
var box = boxes[boxIndex]; // get the box to update position and redraw canvas
if((direction < 0 && box.x >= minX) || (direction > 0 && box.x <= maxX))
{
// move the box in the desired direction multiplied by moveFactor
box.x = box.x + (direction * moveFactor);
invalidate(); // canvas needs redrawing since graphics changed
}
}
ORIGINAL ANSWER:
Arrays use zero-based indexing.
If you have only two paddles, then you should use index 1
, not 2
. To access the first paddle, use 0
, not 1
. Adjust your for loop accordingly by changing instances of checking for 1
to 0
.
For example:
paddles[0].style.backgroundColor="red"; // adjusting for paddle 1
paddles[1].style.backgroundColor="red"; // adjusting for paddle 2
Also, var array = [2]
does not create an array with two elements. It creates an array with one element having an integer value of 2
When dealing with DOM elements, consider something like this:
<div id='paddle1'></div>
<div id='paddle2'></div>
<script type='text/javascript'>
var paddles = [];
paddles[0] = document.getElementById('paddle1');
paddles[1] = document.getElementById('paddle2');
paddles[0].style.backgroundColor="red"; // setting paddle 1 color to red
paddles[1].style.backgroundColor="orange"; // setting paddle 2 color to orange
</script>