Tell me more ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Problem:

When I get to the end of the Grid it gives me an Error :-/

The X axis is fine, the problems occur then I move "over the end" of TOP and BOTTOM.

This code works:

if(new_data[1] == "right"){
            // If New Grid Location is Empty
            if(grid[player_y][player_x  + 1] == 0){
            grid[player_y][player_x] = 0;
            player_x = player_x + 1;
            grid[player_y][player_x] = 1;
            socket.emit("message", "move," + "right");
            }

And this one does not:

if(new_data[1] == "up"){

        // If New Grid Location is Empty
        if(grid[player_y - 1][player_x] == 0){
        grid[player_y][player_x] = 0;
        player_y = player_y - 1;
        grid[player_y][player_x] = 1;
        socket.emit("message", "move," + "up");

It says the error is "Cant == 0 of Undefined"

I assume that the Problem lies in the First Array being less then 0 and therefore giving a Undefined Error on the Second Array..

I fixed this by creating a "Wall" at the X Edges:

for(var i = 0; i < 20; i++){
grid[0][i] = 1;
}
for(var i = 0; i < 20; i++){
grid[19][i] = 1;
}

But why does it not give an Error when I try to access a "undefined" of the Second Array?

share|improve this question
Are you sure when you add 1 you are not adding to something that is NaN ? – Dave Jan 22 at 4:46
1  
Why was my comment deleted if this wasn't migrated? – Byte56 Jan 22 at 6:05
Ditto.. No idea why – Oliver Schöning Jan 22 at 10:07
It wasn't migrated because the OP is unable to ask questions on SO. – Tetrad Jan 22 at 17:12

1 Answer

up vote 2 down vote accepted

That's probably because in here if (grid[player_y - 1][player_x] == 0) you actually do if (grid[0 - 1][player_x] == 0) at some point. Accessing -1 element of array gives you the error.

You need to check your bounds first, before testing with array. Probably like so:

if (player_y >= 0 && player_y < width) && (grid[player_y - 1][player_x] == 0)

I'm not entirely familiar with how JS handles out of range in arrays, is it possible that when you access x+1 JS increases the arrays length or accesses next element at [y+1,0]

share|improve this answer
1  
Yes. It's because you can access any property of anything (including arrays), and if it doesn't exist, you'll just get an undefined value. But if you try to use the undefined value as an array... boom! – MarkR Jan 23 at 23:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.