Friday, July 27, 2012

Handling Mouse Click in Box2D

Often in a game you would want to know the b2Body on which the mouse click occurred .

The co-ordinates for the mouse click can be obtained as follows,
var mouseX, mouseY;
function handleMouseDown(e) {
    mouseX = (e.clientX - canvas.offsetLeft) / SCALE;
    mouseY = (e.clientY - canvas.offsetTop) / SCALE;
    getBodyAtMouse();
}

The b2Body at the Mouse Click can be obtained as follows,
var selectedBody;
function getBodyAtMouse() {
mousePVec = new b2Vec2(mouseX, mouseY);
    var aabb = new b2AABB();
    aabb.lowerBound.Set(mouseX - 0.001, mouseY - 0.001);
    aabb.upperBound.Set(mouseX + 0.001, mouseY + 0.001);
    selectedBody = null;
    world.QueryAABB(getBodyCB, aabb);
    if(selectedBody!= null && selectedBody.GetUserData() != null)
              console.log(selectedBody.GetUserData().name);
    return selectedBody;
}

b2AABB() returns an axis aligned bounding box defined by the upper and lower bounds. I have set the upper and lower bound of the box to the mouse click points. The AABB query returns all fixtures overlapping in the given the rectangular area, the callback function is called for each of the fixture in the bounding box. The callback is usually used to create a list of fixtures/body for further processing.

function getBodyCB(fixture) {
if(fixture.GetShape().TestPoint(fixture.GetBody().GetTransform(), mousePVec)){
                  selectedBody = fixture.GetBody();
    }
}

No comments:

Post a Comment