Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify which object on screen clicked in html5 canvas javascript?

I'm making a game in html5 canvas. I'm using jquery so I can get the click event and the clicks x,y coordinates. I have an array of unit objects and a tiled terrain (also an array). The unit objects have bounding box information, their position, and their type.

What is the most effecient way to map this click event to one of the units?

like image 626
Travis Avatar asked Sep 11 '10 11:09

Travis


1 Answers

Loop through the unit objects and determine which was clicked like so:

// 'e' is the DOM event object
// 'c' is the canvas element
// 'units' is the array of unit objects
// (assuming each unit has x/y/width/height props)

var y = e.pageY,
    x = e.pageX,
    cOffset = $(c).offset(),
    clickedUnit;

// Adjust x/y values so we get click position relative to canvas element
x = x - cOffset.top;
y = y - cOffset.left;
// Note, if the canvas element has borders/outlines/margins then you
// will need to take these into account too.

for (var i = -1, l = units.length, unit; ++i < l;) {
    unit = units[i];
    if (
        y > unit.y && y < unit.y + unit.height &&
        x > unit.x && x < unit.x + unit.width
    ) {
        // Escape upon finding first matching unit
        clickedUnit = unit;
        break;
    }
}

// Do something with `clickedUnit`

Note, this won't handle complex intersecting objects or z-index issues etc... just a starting point really.

like image 108
James Avatar answered Oct 23 '22 12:10

James