WalkOfLife
WalkOfLife

Reputation: 267

Retrieve "id" from array in JQuery

I'm working on a small game and I have several obstacles in an array like so:

obstacles = [ { id: '#car' }, { id: '#house' }, { id: '#door' }, ];

In the second part of my code, I have:

JQuery:

 $('#alert').hide();
 for (index in obstacles) {

        object = $(obstacles[index]["id"]);


    obj_left = object.position().left + parseInt(object.css("margin-left"));
    obj_top = object.position().top + parseInt(object.css("margin-top"));



      if ((((posX > (obj_left - me.width() / 2)) && 
      (posX < (obj_left + object.width() + me.width() / 2)))) && 
     (posY > (obj_top - me.height() / 2)) && 
     (posY < (obj_top + object.height() + me.height() / 2))) {


            // Cannot walk 
            return false;
        }
    $('#alert').show(); // display error message 
    }
    // Can walk again
    return true && $('#alert').hide();   // hide error again                 
}

HTML:

<div id="alert">//...</div>
<div id="character"></div>
<div class="door" id="door"></div>
<div class="house" id="house"></div>
<div class="car" id="car"></div>

I tested it out and it worked great. But instead of displaying an alert for every obstacle, I just want to retrieve the value of a certain obstacle (i.e: if the player hits a car, output "You hit a car!" or if the player hits a house, output "You may not enter").

Hope I've been straightforward and have provided a fair amount of code.

EDIT: Here's a link to the tutorial I followed: http://blog.oscarliang.net/pokemon-online-game-theme-tutorial/

Thanks!

Upvotes: 1

Views: 114

Answers (1)

Zack
Zack

Reputation: 1703

If I understand you correctly, this will do what you want:

note: you'll need to include jQuery for this to work of course

<script>
         obstacles = [ { id: 'car' }, { id: 'house' }, { id: 'door' }, ]
         $("div").on("click", function() {
             var found = false;
             var obj   = $(this).prop("id");
             for(i=0;i<obstacles.length;i++) {
                 if(obstacles[i].id == obj) {
                        found = true;                     
                 }
             }
             alert(found ? "You hit a " + obj + "!" : "You may not enter");
         });
</script>

<div id="car">Car</div>
<div id="house">house</div>
<div id="door">door</div>
<div id="bank">bank</div>

Upvotes: 1

Related Questions