Unity3D has the OnCollisionEnter2D
, OnCollisionExit2D
, OnTriggerEnter2D
etc. However, I am using Box2D and am looking for a way to implement something similar or the same in my C project, but I do not know how. I saw something about implementing a listener but I believe it was for the whole world. I am looking to report these events only to the code that physics body is attached to.
CodePudding user response:
Enabling an event listener is necessary for collision events in Box2D, as explained in this video. Alternatively, you could implement your own collision logic. For rectangular hitboxes, that would look something like this: (Please note: this only works for rectangles with no rotation relative to the screen.)
if (rect1.x < rect2.x rect2.w &&
rect1.x rect1.w > rect2.x &&
rect1.y < rect2.y rect2.h &&
rect1.h rect1.y > rect2.y)
{
// collision detected
}
else
{
// no collision
}
For circles, that would look something like this:
auto dx = (circle1.x circle1.radius) - (circle2.x circle2.radius);
auto dy = (circle1.y circle1.radius) - (circle2.y circle2.radius);
auto distance = sqrt(dx * dx dy * dy);
if (distance < circle1.radius circle2.radius)
{
// collision detected
}
else
{
// no collision
}
You can see these detection algorithms in more detail here.
CodePudding user response:
Accoring to the api doc, OnCollisionEnter2D
is bind to the object itself, so it meet your needs.
Simply, you can add collision detection code in the ego object and do something when a collision is detected.
class Car {
void process() {
if (checkCollision(box2d)) {
// do something
}
}
};