Hi, I am really big noob and I cannot really write this part of code.
I need to write collision detection response on 2D box colliders(AABB), so no rotation involved.
Here is my function, please could you incorportate collision response into it? I`ve been trying for past 5 hours and nothing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void BoxCollider::BoxVsBox(Collider* collider)
{
UpdateColliderSize();//Function will just update width and height variable of collider
//Get other Box collider
BoxCollider* otherBoxCollider = dynamic_cast<BoxCollider*>(collider);
otherBoxCollider->UpdateColliderSize();
//Check if colliders collide
if (gameObject->transform->position.x + width > otherBoxCollider->gameObject->transform->position.x &&
gameObject->transform->position.x < otherBoxCollider->gameObject->transform->position.x + otherBoxCollider->width &&
gameObject->transform->position.y + height > otherBoxCollider->gameObject->transform->position.y &&
gameObject->transform->position.y < otherBoxCollider->gameObject->transform->position.y + otherBoxCollider->height)
{
//We have a collision, need collision response for both objects here, so both move from each others side depends on collision depth
}
}
To make code easier to read and write, consider using references. When doing this, I like to add the comment //shorthand to make it clear why I'm creating the reference. Your example could be rewritten like this:
Your code will fail if one box is contained completely within the other. It's easier to write code that detects if the boxes *don't* intersect. Then just invert it to see if they *do* intersect.
Two boxes b1 and b2 don't intersect if:
1 2 3 4
b1.top < b2.bottom // b1 below b2
|| b2.top < b1.bottom // b2 below b1
|| b1.right < b2.left // b2 to the right of b1
|| b2.right < b1.left // b1 to the right of b2
When translating this to your code, be sure to consider off-by-one errors.
Or is it better to have references rather? It`s true I wouldn`t have to use ->. When is it appropriate for variable to be rather reference than pointer?