If the user clicks on the screen, is there a better way to find the nearest body than looping through each one and finding the distance between each body's center and the clicked point?
How to find the nearest body?
Java🙂 yes, there's a much better way. which version are you using? I'm assuming the 2.0.1 one. Basically you want to just use the collision detection of jbox2d, as that's part of what it's made for.
(this was copied and pasted from the testbed)
shapes is now your shapes that have collided with your tiny box!
Code:
// let's say p is the mouse point in world coordinates,
// and aabb is a pooled AABB object,
// and d is a pooled Vec2(0.001f, 0.001f)
aabb.lowerBound.set(p);
aabb.lowerBound.subLocal(d);
aabb.upperBound.set(p);
aabb.upperBound.addLocal(d);
// Query the world for overlapping shapes.
int k_maxCount = 10;
Shape shapes[] = m_world.query(aabb, k_maxCount);
// and aabb is a pooled AABB object,
// and d is a pooled Vec2(0.001f, 0.001f)
aabb.lowerBound.set(p);
aabb.lowerBound.subLocal(d);
aabb.upperBound.set(p);
aabb.upperBound.addLocal(d);
// Query the world for overlapping shapes.
int k_maxCount = 10;
Shape shapes[] = m_world.query(aabb, k_maxCount);
(this was copied and pasted from the testbed)
shapes is now your shapes that have collided with your tiny box!
In the query method, is there any guarantee of the order in which the returned array will be? I want to find the nearest shape within a certain distance, but if multiple shapes are within that distance, will I have to loop through the returned shapes to find the nearest one, or would they be sorted from nearest to furthest?
No, the returned order has to do with the way the dynamic tree is structured, so for all purposes just assume it's not in any order. Any further processing (like finding the closest) can be done by you. But unless you have a bunch of overlapping objects, you should only get one result.
Original thread: https://box2d.org/forum/viewtopic.php?t=5748