I wanted to ask, how do I resolve collision between 2 cubes - in my case I want to push a moving / dynamic cube (used for the player) out of another static cube (used for the floor or objects in the scene)?
I tried various things, but in the end I don't know how to make the dynamic cube stay smoothly on top of the floor or not able to go through other objects (everything AABB vs AABB for now).
Below are the most important snippets to understand my problem better.
From PhysicsEngine.cpp
IntersectData intersectData =
m_objects[i]->getCollider().intersect(
m_objects[j]->getCollider());
// if they intersect, reverse movement to have solid box collisions.
if(intersectData.getDoesIntersect())
{
// revert movement (later push?) collision response.
glm::vec3 diff = m_objects[i]->getPosition() - m_objects[j]->getPosition();
glm::vec3 sep = glm::normalize(intersectData.getDirection()) * diff;
// std::cout << "Separation between: " << m_objects[i]->
// if testCollisionResponse - push back.
if (m_objects[i]->testCollisionResponse)
{
m_objects[i]->setPosition(m_objects[i]->getPosition() + sep);
// m_objects[i]->setVelocity(glm::vec3(0.0));
// m_objects[i]->testGravity = false;
// m_objects[i]->testGravity = false;
}
else if (m_objects[j]->testCollisionResponse)
{
m_objects[j]->setPosition(m_objects[j]->getPosition() - sep);
// m_objects[j]->setVelocity(glm::vec3(0.0));
// m_objects[j]->testGravity = false;
}
}
AABB.cpp
uGE::IntersectData uGE::AABB::intersectAABB(const AABB& other) const
{ glm::vec3 distances1 = other.getMinExtents() - m_maxExtents;
// test the other way around.
glm::vec3 distances2 = m_minExtents - other.getMaxExtents();
// pick the biggest values between the vectors on each axis.
glm::vec3 distancesOnEachAxis = glm::max(distances1, distances2);
float maxDistance = distancesOnEachAxis[0];
for (int i = 0; i < 3; i++)
{
if (distancesOnEachAxis[i] > maxDistance)
{
maxDistance = distancesOnEachAxis[i];
}
}
return uGE::IntersectData(maxDistance < 0, distancesOnEachAxis);
}
IntersectData.hpp
class IntersectData
{ public: IntersectData(const bool doesIntersect, const glm::vec3 direction) : m_doesIntersect(doesIntersect), m_direction(direction) {}
inline bool getDoesIntersect() const { return m_doesIntersect; }
inline float getDistance() const { return glm::length(m_direction); }
inline const glm::vec3 getDirection() const { return m_direction; }
private: const bool m_doesIntersect; const glm::vec3 m_direction; };
These are the project files (if you want to see more): https://github.com/BigThinker/CPPGame/blob/master/uGE/uGE/Physics/PhysicsEngine.cpp
All the best, Aldo