Moving Divs in JavaScript with key presses

84 views Asked by At

I'm doing an HTML/JavaScript based game, the game objective is 2 monsters collecting cakes and avoid other thing than cakes. I've created 2 divs where each one is the zone where I want the characters to move around. First i'm starting with just the basic (Space key to Jump), but this is one of those games that if one character goes up, the other one comes down. For now, i'm testing the code to just one character to see if it works, if it does i'm planning to program to the other character do the opposite. This is the code I got for the Key Presses:

function onKeyPressed(event) {
    if(event.keyCode == 37) {
        left = true;
    }
    if(event.keyCode == 39) {
        right = true;
    }
    if(event.keyCode == 38) {
        up = true;
    }
    if(event.keyCode == 40) {
        down = true;
    }
    if(event.keyCode == 32) {
    updateMonster1Place();
    updateMonster2Place();
    }
}

// function to be called when a key, in the keyboard, is released
function onKeyReleased(event) {
    if(event.keyCode == 37) {
        left = false;
    }
    if(event.keyCode == 39) {
        right = false;
    }
    if(event.keyCode == 38) {
        up = false;
    }
    if(event.keyCode == 40) {
        down = false;
    }
}

And this is the first function called updateMonster1Place();

function updateMonster1Place() {

    if (monster1.top >= 500){
    for( var i=0; i = 100; i++){
    monster1.top = i + "px";
        }
    }
}

I think this code is wrong, because, my character is placed at Top = 500px, and what I want to happen, is to the character slide, and just stops when his Top = 100.

I hope you understand what im trying to do here. Thanks in advance!

0

There are 0 answers