50 lines
1.5 KiB
C++
50 lines
1.5 KiB
C++
#include "components/ColliderComponent.hpp"
|
|
|
|
#include "Entity.hpp"
|
|
#include "components/TransformComponent.hpp"
|
|
|
|
void ColliderComponent::Setup() {}
|
|
|
|
void ColliderComponent::EmitCollision(Entity &other) {
|
|
for (auto &callback : onCollision) {
|
|
callback(other);
|
|
}
|
|
}
|
|
|
|
void ColliderComponent::AddCollisionListener(std::function<void(Entity &)> callback) {
|
|
onCollision.push_back(std::move(callback));
|
|
}
|
|
|
|
void ColliderComponent::Update(float) {
|
|
if (!monitoring || !context || !context->entities || entity->queuedForFree) {
|
|
return;
|
|
}
|
|
|
|
auto selfTransform = entity->GetComponent<TransformComponent>();
|
|
if (!selfTransform) {
|
|
return;
|
|
}
|
|
|
|
for (auto &other : *context->entities) {
|
|
if (!other || other.get() == entity || other->queuedForFree) {
|
|
continue;
|
|
}
|
|
|
|
auto otherCollider = other->GetComponent<ColliderComponent>();
|
|
auto otherTransform = other->GetComponent<TransformComponent>();
|
|
if (!otherCollider || !otherTransform || !otherCollider->get().monitorable) {
|
|
continue;
|
|
}
|
|
|
|
const float dx = selfTransform->get().x - otherTransform->get().x;
|
|
const float dy = selfTransform->get().y - otherTransform->get().y;
|
|
const float r = radius + otherCollider->get().radius;
|
|
if ((dx * dx + dy * dy) <= (r * r)) {
|
|
// collision emitted per frame keeps gameplay reactive without physics bodies
|
|
EmitCollision(*other);
|
|
}
|
|
}
|
|
}
|
|
|
|
void ColliderComponent::Cleanup() {}
|