Question

So I'm making a little roguelike game in Javascript and have an error with a piece of my rendering code. Not the rendering itself but a little sub-part of it that iterates over an array of objects, checking if any of the objects have coordinates that match the x and y parameters, then returning the object if coordinates match.

Here's the code giving me trouble

Client.Render.checkObjects = function(objects, x, y) {
    for (var a = 0; a < objects.length; a++) {
        if (objects[a].x == x && objects[a].y == y) {
            return objects[a];
        } else {
            return false;
        }
    }
};

I have an array of objects called testSnap.objects which I made like this:

function testObject(x, y) {
    this.x = x;
    this.y = y;
    this.symbol = "a";
};
testSnap.objects.push(new testObject(5,5));
testSnap.objects.push(new testObject(3,5));

I then try

console.log(Client.Render.checkObjects(testSnap.objects, 5, 5));
console.log(Client.Render.checkObjects(testSnap.objects, 3, 5));

Which returns:

Object { x: 5, y: 5, symbol: "a" }
false

It seems objects[a] is never objects[1]?

Was it helpful?

Solution

You'll only ever return an object if the first object matches. If it doesn't, you're immediately returning false. Try:

Client.Render.checkObjects = function(objects, x, y) {
  for (var a = 0; a < objects.length; a++) {
    if (objects[a].x == x && objects[a].y == y) {
        return objects[a];
    }
  }

  // NOW return false if we never matched
  return false;
};

OTHER TIPS

Your return false statement needs to be after your for loop; otherwise false will be returned when the first object does not match.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top