1

I'm trying to make a game and still in the opening stages, I have the character and the code I thought would work, except when I run it nothing happens. I cant seem to find an error in it.

document.body.onkeydown = function(event){

    var k = event.keyCode; 
    var chr = {
        updown: function (){
            var y = 0;
            if (k==38)  {
                --y;
            } else if (k == 40) {
                ++y;
            }
            return y; 
        },
        leftright: function (){
            var x = 0;
            if (k == 37) {
                --x;
            } else if (k == 39) {
                ++x;
            }
            return x; 
        }
    };

    rogue.style.top = (chr.updown()) + "px";
    rogue.style.left = (chr.leftright()) + "px";
}
#rogue {
    position: relative;
    top: 0px;
    left: 0px;
}
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="jumpOPP.css">
        <script src="jumpOPP.js"></script>
    </head>
    <body>
        <img id="rogue" src="http://piq.codeus.net/static/media/userpics/piq_143310_400x400.png" >
    </body>
</html>

I would appreciate any help at all.

Cœur
  • 37,241
  • 25
  • 195
  • 267

5 Answers5

0

Wrap your function like this:

document.body.onkeydown = function(event){
    // Your event here
};

Take the handler off the body tag too.

JSFIDDLE

Equalsk
  • 7,954
  • 2
  • 41
  • 67
  • 1
    He's already got that. Admittedly, I prefer your approach but he does have it. Look at the body tag. – Reinstate Monica Cellio Jul 06 '15 at 08:56
  • Yeah, and his never subscribes to the move event, mine does and works fine. His code to move the Rogue isn't great, but that's not that I'm looking at. – Equalsk Jul 06 '15 at 08:58
  • His code does hook to the event fine. Admittedly your is better practice, but his will work without issue. The event hook is not the problem. – Rory McCrossan Jul 06 '15 at 08:59
  • I can see his body tag... Have you tested his code? Running it verbatim doesn't work, it never subscribes to that event handler, changing it as I suggested works perfectly. Granted the code he uses to move the rogue isn't up to much, but that isn't my fault. – Equalsk Jul 06 '15 at 09:02
  • it moves but only slightly and only once, how do i make it keep moving in the diorection i want until i take my hand off the keys?? – Christopher O'Brien Jul 06 '15 at 09:02
  • What are you expecting to happen? The code I provided is working and listens to the move function. Your move function only moves the rogue 1 pixel in any direction so is hard to see. Are you sure you're not just missing it? – Equalsk Jul 06 '15 at 09:03
  • i noticed that, sorry – Christopher O'Brien Jul 06 '15 at 09:06
  • Oh, you didn't mention that. Rory has is pegged then, you're resetting the Y/X position to 0 every time before you moved it. You need to get the existing position an add/subtract 1 as appropriate as he shows. – Equalsk Jul 06 '15 at 09:07
0

The logic you're using to set the top and left values is a little off. Note also that you need to parse the value to an integer so that you can add/remove from its value, and also provide a default.

Try this:

document.body.onkeydown = function(event){
    var rogue = document.getElementById('rogue');
    var currentY = parseInt(rogue.style.top || 0, 10);
    var currentX = parseInt(rogue.style.left || 0, 10);
    var speed = 3;

    switch (event.keyCode) {
        case 38: // up;
            rogue.style.top = (currentY - speed) + 'px';
            break;
        case 40: // down;
            rogue.style.top = (currentY + speed) + 'px';
            break;
        case 37: // left;
            rogue.style.left = (currentX - speed) + 'px';
            break;
        case 39: // right;
            rogue.style.left = (currentX + speed) + 'px';
            break;
    }
}

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Change your function as below (its just a sample) Suggested reading: Retrieve the position (X,Y) of an HTML element

...

updown: function (){
            var y = CURRENT_Y; // Get the current Y position of the image HERE
            if (k==38)  {
                --y;
            } else if (k == 40) {
                ++y;
            }
            return y; 
        },
        leftright: function (){
            var x = CURRENT_X; // Get the current X position of the image HERE
            if (k == 37) {
                --x;
            } else if (k == 39) {
                ++x;
            }
            return x; 
        }
Community
  • 1
  • 1
Tismon Varghese
  • 849
  • 1
  • 6
  • 17
0

Perfectly Working Answer: Run the Code Snippet and check

//bind an event when the user presses any key
window.onkeydown = function (e) {
    if (!e) {
        e = window.event;
    }
    //The event object will either be passed
    //to the function, or available through
    //window.event in some browsers.

    var code = e.keyCode;
    //that's the code of the key that was pressed.
    //http://goo.gl/PsUij might be helpful for these.

    //find our rouge image
    var rouge = document.getElementById("rouge");

    //get the image's current top and left position.
    //rouge.style.top will find the top position out of our
    //style attribute; parseInt will turn it from for example '10px'
    //to '10'.

    var top = parseInt (rouge.style.top, 10);
    var left = parseInt (rouge.style.left, 10);
    
    //We'll now compare the code that we found above with
    //the code of the keys that we want. You can use a chart
    //like the one in http://goo.gl/PsUij to find the right codes,
    //or just press buttons and console.log it yourself.

    if ( code == 37 ) { //LEFT

    //time to actually move the image around. We will just modify
    //its style.top and style.left accordingly. If the user has pressed the
    //left button, we want our player to move closer to the beginning of the page,
    //so we'll reduce the 'left' value (which of course is the distance from '0' left)
    //by 10. You could use a different amount to make the image move less or more.

    //we're also doing some very basic boundary check to prevent
    //the image from getting out of the page.

        if ( left > 0 ) {
            rouge.style.left = left - 10 + 'px';
        }
    } else if ( code == 38 ) { //UP
        //if we pressed the up button, move the image up.
        if ( top > 0 ) {
            rouge.style.top = top - 10 + 'px';
        }
    } else if ( code == 39 ) { //RIGHT
        //move the image right. This time we're moving further away
        //from the screen, so we need to 'increase' the 'left' value.
        //the boundary check is also a little different, because we're
        //trying to figure out if the rightmost end of the image 
        //will have gone
        //further from our window width if we move it 10 pixels.

        if ( left+rouge.width+10 < window.innerWidth ) {
            rouge.style.left = left + 10 + 'px';
        }
    } else if ( code == 40 ) { //DOWN
        if ( top+rouge.height+10 < window.innerHeight ) {
            rouge.style.top = top + 10 +'px';
        }
    }
}
<img src="http://piq.codeus.net/static/media/userpics/piq_143310_400x400.png" id="rouge" style="position:absolute;top:0px;left:0px" />
0

Try this :

Create an array to hold key states : window.keyStates[];

Update the keyStates var with onkeyup / onkeydown events.

document.body.onkeydown = function (event) {
    window.keyStates[event.keyCode] = true;
}
document.body.onkeyup = function (event) {
    window.keyStates[event.keyCode] = false;
}

Create a loop to loop game :

var mainLoop = function () {
    if (window.keyStates[38]) dostuff ();
    if (window.keyStates[40]) dootherstuff ();
    // etc....
}

window.setInterval(function() {mainLoop()}, 100);

The code is glitchy but you get the idea ? This way you can move your toon 2 directions at the same time too. Or manage virtually any key pressed at the same time.

PinkTurtle
  • 6,942
  • 3
  • 25
  • 44
  • I did a typo. If using this code don't use `else if`s in the `mainLoop` func, rather use plain `if`s. This way you can handle several keys pressed at the same time. – PinkTurtle Jul 07 '15 at 11:23