yupplemayham/YuppleMayham/include/gameplay/physics.h

70 lines
No EOL
2.2 KiB
C++

#ifndef _H_PHYSICS_H
#define _H_PHYSICS_H
#include <glm/glm.hpp>
#include <vector>
#include <memory>
class EventManager;
struct PhysicsComponent {
bool isBullet = false;
// This ID holds the ID of the gameactor that owns this object, that being themselves or a bullet.
unsigned int ID = 0; // If the ID stays 0 then that object has no owner and will be uncollidable
struct RigidBody {
glm::vec3 position;
glm::vec3 velocity;
glm::vec3 acceleration;
float elasticity = 0.7f;
float mass = 1.0f;
void applyForce(glm::vec3 dir, float mag) {
acceleration += ((dir * mag) / mass);
}
}rigidBody;
struct Collider {
enum class Shape { Square, Circle } shape = Shape::Circle;
glm::vec3 offset = glm::vec3(0.f);
glm::vec3 dimensions;
}collider;
};
class PhysicsComponentFactory {
public:
static PhysicsComponent makeBullet(const unsigned int ID, const glm::vec3& pos, float mass, float radius) {
PhysicsComponent p;
p.ID = ID;
p.rigidBody.position = pos;
p.rigidBody.mass = mass;
p.collider = { PhysicsComponent::Collider::Shape::Circle, glm::vec3(radius, radius, 0.f), glm::vec3(radius) };
p.isBullet = true;
return p;
}
};
class PhysicsEngine {
public:
PhysicsEngine() {}
using CollisionPair = std::pair<PhysicsComponent*, PhysicsComponent*>;
void hookEventManager(const std::shared_ptr<EventManager>& eventManager);
std::shared_ptr<PhysicsComponent> createObject(const unsigned int ID, const glm::vec3& pos, float mass, PhysicsComponent::Collider::Shape shape, glm::vec3 dimensions, glm::vec3 offset = glm::vec3(0.f));
void loadCollisionMap(const std::vector<std::vector<int>>&, float tileSize);
void addObject(const std::shared_ptr<PhysicsComponent>&);
void removeObject(const std::shared_ptr<PhysicsComponent>&);
void update(double deltaTime);
private:
void resolveWorldCollision(const std::shared_ptr<PhysicsComponent>&);
void resolvePossibleCollisions();
void getPossibleCollisions();
int getTileCollider(const glm::vec3& position);
std::vector<std::shared_ptr<PhysicsComponent>> objects;
std::vector<CollisionPair> objCollisions;
std::vector<std::vector<int>> collisionMap;
float tileSize = 32.f;
std::shared_ptr<EventManager> eventManager;
};
#endif //_H_PHYSICS_H