Currently, my code works in a way that it moves both images with the same arrow keys, i want each image to move interdependently with different key events. The idea is to get sq 1 moving up and down a background image using the up and down arrow keys, with sq 2 doing the same with the w and s keys.
Any help or advice will be greatly appreciated.
Code:
var x = 0;
var y = 0;
var sq1 = document.getElementById("sq1");
var sq2 = document.getElementById("sq2");
function move_up() { y--; } //down
function move_down() { y++; } //up
function key_down(key_code) {
user_key = key_code;
console.debug("::"+key_code);
}
function key_up() {
user_key = 0;
}
function loop()
{
var sq1 = document.getElementById("sq1")
sq1.style.position = "absolute";
sq1.style.left = x+"px";
sq1.style.top = y+"px";
window.setTimeout("loop()", 10);
if(user_key == 40) { y++;
}
if(user_key == 38) {
y--;
}
var sq2 = document.getElementById("sq2");
sq2.style.position = "absolute";
sq2.style.left = x+"px";
sq2.style.top = y+"px";
window.setTimeout("loop()", 10);
if(user_key == 83) { y++;
}
if(user_key == 87) {
y--;
}
}
function on_load() {
window.addEventListener('keydown', function(evt) {
key_down(evt.keyCode);
},true);
window.addEventListener('keyup', function(evt) {
key_up();
},true);
loop();
}