1

I have an array of Nodes 'flags', and I want to set my object's position at the first object in that array, it works and the object actually gets positioned as intended, but when I make the comparison it fails and logs 'NO'.

The line of code that sets the position works, but the comparison fails, what's wrong here?!

start: function () {
        this.node.position = this.flags[0].position;
        this.movement();
    },
    movement: function() {
       if (this.node.position == this.flags[0].position) {  // Problem
           console.log("YES");
       }
       else {
           console.log("No");

Update:

When I do it like this it works:

if (this.node.position.x == this.flags[0].position.x) // or position.y
Abdou023
  • 1,654
  • 2
  • 24
  • 45

1 Answers1

1

Well if you write javascript here (and it looks like you do) there're two things you should know:

  1. You can't compare objects with == out of the box

    ({"a":1} == {"a":1}) Will return false (you may try it yourself in your browser. As a workaround you could do something like:

    function posCompare(p1, p2){ return p1.x === p2.x && p1.y === p2.y; }

Then use it instead of == for positions

  1. See how I use === instead of ==? Second thing to know is Use only ===. You can learn the difference Which equals operator (== vs ===) should be used in JavaScript comparisons? but I'd keep away from == anywhere. It's slower, it may cause strange errors here and there - just don't use it at all
Community
  • 1
  • 1
  • Wait a sec. You wrote comparing position.x-es works (which is inaccurate because you need to check both coordinates) What makes you think 'if (this.node.position.x === this.flags[0].position.x && this.node.position.y == this.flags[0].position.y)' won't work? (perhaps the values are actually different??) – Роман Гуйван Mar 21 '16 at 07:51
  • 1
    I was talking about === rather than ==, but yeah, your way works, but I don't understand why my original code will not work, it's massive hassle to keep comparing both x && y like that. In other game engines the position comparison works fine. – Abdou023 Mar 21 '16 at 08:35
  • As I've stated there's no build-in comparison of objects in javascript. You can import a js-library just for that if you want to, or perhaps define a function for equality check, but sadly that's just how the things are. – Роман Гуйван Mar 21 '16 at 13:02