0

I am using vanilla tilemaps, I am not sure if there is software out there related to tilemaps, but if there is be assured I am just using plain javascript, I have an issue though, I want to move the x of a player when a button is pressed, but it doesn't move, the player is green, and is identified by the number 4 on the tilemap.

it registers that I press the button(in console), but doesn't move the player at all, can anyone point out the issue? look at lines 62-89, thats where the error mostly occurs except for some global variables.

here's a link to the jsfiddle, I used this because I needed to show that the blocks don't move. http://jsfiddle.net/8jr2ha3h/

var playerY = 0;
var playerX = 0;
var moveLeft = 65;
var moveRight = -65;

//THE PLAYER
player.onload = function(){
    for(var i = 0; i < mapArray.length; i++){
        for(var j = 0; j < mapArray[i].length; j++){
            if(mapArray[i][j]==4){
                context.drawImage(player, playerX, playerY, 45,37);
            }

            playerX+=45;
        }
        playerX = 0;
        playerY +=37;
    }
};

//KEY FUNCTIONS
document.onkeydown = function(e) {
//identifying that it's a window event.
    e = e || window.event;
    switch(e.which || e.keyCode) {
        //37 is key for left arrow.
        case 37:
        {
            playerX = playerX - moveLeft;
            console.log(playerX);
            console.log('left');
        }
        break;
    }
}    
Alkis Kalogeris
  • 17,044
  • 15
  • 59
  • 113
  • Your code successfully updates the `playerX` variable. However there is no code that repaints the canvas and therefore the player doesn't move. – Afsa Aug 25 '14 at 22:00
  • would i repaint it inside the case37? how would I go about that? – user3843041 Aug 25 '14 at 22:44

1 Answers1

0

Seems as though you're only drawing the player in player.onload(). You'll likely want to have all the rendering code in a single render() function, and possibly call that in player.onload() and then also call that function whenever the screen changes (the player moves, enemies move/die, the map changes for whatever reason... there are any number of reasons you'd need to redraw).

You may want to consider a main game loop here, which would (very simply) be something to the effect of:

while (true) { checkForInputFromThePlayer(); // this can update player coordinates, etc doSomeAI(); // Move some enemies around, have them attack the player render(); }

EDIT: A great example of a Game Loop can be seen in yckart's answer to requestAnimationFrame at a limited framerate

Community
  • 1
  • 1
v4nz
  • 115
  • 7