2

I am currently making a small scrolling canvas game, and I am trying to implement monsters. I keep two arrays for the monsters, one for their x positions and one for their y positions. For some unexpected reason, both of the arrays get filled up to 1152 elements, two of them are predefined, and the others are all "NaN".

Here's a link to the program: http://codepen.io/kenshin791011/pen/WpxQmg

(The function monsterMove is run on key down)

var monsterx = [13, 5],
    monstery = [41, 42];
function monsterMove() {
    for(var i = 0; i < monsterx.length; i++) {
        var z = Math.floor(Math.random() * 4);
        switch(z) {
            case 0:
                monsterx[i] -= 1;
                break;
            case 1:
                monstery[i] -= 1;
                break;
            case 2:
                monsterx[i] += 1;
                break;
            case 3:
                monstery[i] += 1;
                break;
        }
    }
}
2
  • 3
    Not what you're asking, but did you ever think of storing the X and Y coordinates together: monsters = [{x:13,y:41}, {x:5,y:42}]? Just seems neater to me. Commented Mar 5, 2017 at 0:30
  • Oh, I didn't know that I could do that XD Commented Mar 5, 2017 at 0:58

1 Answer 1

1

The following loop from the JS in your codepen is updating the monsterx array for elements 0 through to cGrid.length:

for(var i = 0; i < cGrid.length; i++) {
    pGridx[i] += g;
    monsterx[i] += 1;
}

Given that the first time monsterx[i] is undefined for almost all of those indices, and undefined + 1 is NaN, that's how you get an array full of NaN - except for the first two elements that started with valid numbers.

You have a similar loop that updates monstersy.

(For future reference, if you're not sure how a variable is being updated, the first step would be to search through the code for that variable. That's all I did to find the problem above.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help! I'll make sure that I'll follow your tip whenever something like this happens again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.