问题
A small rectangle is lobbed toward a larger rectangle. I want to know if it hits the large rectangle in "the side" or on "the top".
I'd also like to detect if the smaller polygon comes to rest on its own side, top, or bottom. I'm going to imagine this will entail using GetAngle() on the body to detect how it is oriented, but I'd like to hear if there is a better way.
Thanks
回答1:
You could create your "object collided with" as multiple fixtures. Use a polygon or square shape for the main fixture. Then attach several zero mass fixtures around the perimeter as "Sensors" and use the usertags in all of them to determine which one got hit on a collision.
This image shows the basic idea:
By doing it this way, Box2D will handle all the work of dealing with the angle you were at when you impacted or what got impacted first.
This technique is not just for a box with four sides. You can use it for any body where you need to have collisions do "different things" based on where they collide.
NOTE: You may want to turn on continuous collision detection and/or set your small box to be a "bullet" so that it can't tunnel through one of your sensors. Or make the sensors really large (more expanding into the main target's shape). Or you can make the simulation steps smaller (small fixed time) so that the distance traveled during a simulation step is much smaller than the width of your edge contact fixtures. The goal of either of these ideas is to avoid "tunneling".
If you don't use the sensor approach, you could try to do this with geometry and the velocity vectors and rotational angles (at the time of just before impact) for each of the two bodies involved, but that sounds kind of painful.
Was this helpful?
来源:https://stackoverflow.com/questions/23203687/box2d-how-to-detect-which-side-of-a-polygon-gets-collision