0
0
mirror of https://github.com/Nimac0/SDL_Minigame synced 2026-01-12 23:33:41 +00:00

Merge pull request #21 from Nimac0/collision-manager

Rewrote collision logic
This commit is contained in:
Freezarite 2024-01-30 03:28:45 +01:00 committed by GitHub
commit 2be05e8b9c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 532 additions and 207 deletions

View File

@ -30,4 +30,10 @@ target_link_libraries(${PROJECT_NAME} PRIVATE
SDL2_mixer::SDL2_mixer-static SDL2_mixer::SDL2_mixer-static
) )
if(CMAKE_BUILD_TYPE MATCHES "Debug")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fsanitize=address -fno-omit-frame-pointer")
target_link_libraries(${PROJECT_NAME} PRIVATE "-fsanitize=address")
endif()
file(COPY ${PROJECT_SOURCE_DIR}/assets DESTINATION ${PROJECT_BINARY_DIR}) file(COPY ${PROJECT_SOURCE_DIR}/assets DESTINATION ${PROJECT_BINARY_DIR})

View File

@ -1,3 +1,5 @@
#include "Entity.h"
#include <SDL_render.h> #include <SDL_render.h>
#include <SDL_mixer.h> #include <SDL_mixer.h>
#include <map> #include <map>
@ -13,7 +15,7 @@ public:
AssetManager(Manager* manager); AssetManager(Manager* manager);
~AssetManager(); ~AssetManager();
void createProjectile(Vector2D pos, Vector2D velocity, bool source, int scale, int range, int speed, const char* texturePath); void createProjectile(Vector2D pos, Vector2D velocity, int scale, int range, int speed, const char* texturePath, TeamLabel teamLabel);
//texture management //texture management
void addTexture(std::string id, const char* path); void addTexture(std::string id, const char* path);

View File

@ -0,0 +1,67 @@
#pragma once
#include "ColliderComponent.h"
#include "Constants.h"
#include "Entity.h"
#include "SDL_rect.h"
#include "SpriteComponent.h"
#include "Vector2D.h"
#include "Manager.h"
#include <bitset>
#include <initializer_list>
#include <tuple>
#include <utility>
#include <vector>
class ColliderComponent;
class Entity;
constexpr uint8_t DIRECTION_C = 4;
enum class direction
{
LEFT = 0,
RIGHT,
UP,
DOWN
};
using IntersectionBitSet = std::bitset<DIRECTION_C>;
class CollisionHandler
{
private:
Manager& manager;
public:
CollisionHandler(Manager& mManager) :
manager(mManager) { };
~CollisionHandler();
static IntersectionBitSet getIntersection( // intersections relative to entityA
Entity* entityA,
Entity* entityB,
Vector2D posModA = Vector2D(0,0),
Vector2D posModB = Vector2D(0,0));
static IntersectionBitSet getIntersectionWithBounds( // will fail to determine direction if speed high enough to switch from no collision to full overlap in one tick
Entity* entity,
Vector2D posMod = Vector2D(0,0));
// temporary function, remove once game.cpp cleaned up
std::vector<ColliderComponent*> getColliders(
std::initializer_list<GroupLabel> const& groupLabels,
std::initializer_list<TeamLabel> const& teamLabels = {},
bool negateTeam = false);
template<typename T>
T getAnyIntersection(
Entity* entity,
Vector2D posMod = {},
std::initializer_list<GroupLabel> const& groupLabels = {},
std::initializer_list<TeamLabel> const& teamLabels = {},
bool negateTeam = false);
void update();
};

View File

@ -2,16 +2,6 @@
class Entity; class Entity;
enum class GroupLabel
{
MAP,
PLAYERS,
ENEMIES,
COLLIDERS,
PROJECTILE,
HEARTS
};
class Component class Component
{ {
public: public:

View File

@ -3,11 +3,13 @@
#include <cstddef> #include <cstddef>
using Group = std::size_t; using Group = std::size_t;
using Team = std::size_t;
constexpr int CHARACTER_COUNT = 4; constexpr int CHARACTER_COUNT = 4;
constexpr std::size_t MAX_COMPONENTS = 32; constexpr std::size_t MAX_COMPONENTS = 32;
constexpr std::size_t MAX_GROUPS = 32; constexpr std::size_t MAX_GROUPS = 32;
constexpr std::size_t MAX_TEAMS = 8; //
constexpr int SCREEN_SIZE_HEIGHT = 640; constexpr int SCREEN_SIZE_HEIGHT = 640;
constexpr int SCREEN_SIZE_WIDTH = 800; constexpr int SCREEN_SIZE_WIDTH = 800;

View File

@ -1,2 +1 @@
#pragma once #pragma once

7
include/Direction.h Normal file
View File

@ -0,0 +1,7 @@
#pragma once
enum class Direction
{
LEFT,
RIGHT
};

View File

@ -5,6 +5,7 @@
#include <bitset> #include <bitset>
#include <vector> #include <vector>
#include "ColliderComponent.h"
#include "ECS.h" #include "ECS.h"
#include "Constants.h" #include "Constants.h"
@ -15,20 +16,49 @@ using ComponentBitSet = std::bitset<MAX_COMPONENTS>;
using GroupBitSet = std::bitset<MAX_GROUPS>; using GroupBitSet = std::bitset<MAX_GROUPS>;
using ComponentArray = std::array<Component*, MAX_COMPONENTS>; using ComponentArray = std::array<Component*, MAX_COMPONENTS>;
enum class GroupLabel
{
MAPTILES,
PLAYERS,
ENEMIES,
COLLIDERS,
PROJECTILE,
HEARTS
};
enum class TeamLabel
{
NONE,
BLUE,
RED
};
class Entity class Entity
{ {
public: public:
explicit Entity(Manager& mManager) : manager(mManager) { } explicit Entity(Manager& mManager) :
manager(mManager) { };
void update() const; void update() const;
void draw() const; void draw() const;
bool isActive() const { return this->active; } bool isActive() const { return this->active; }
void destroy() { this->active = false; } void destroy() {
this->active = false;
if (this->hasComponent<ColliderComponent>()) {
this->getComponent<ColliderComponent>().removeCollision();
}
}
bool hasGroup(Group mGroup); bool hasGroup(Group mGroup);
void addGroup(Group mGroup); void addGroup(Group mGroup);
void delGroup(Group mGroup); void delGroup(Group mGroup);
std::bitset<MAX_GROUPS> getGroupBitSet();
void setTeam(TeamLabel teamLabel);
TeamLabel getTeam();
Manager& getManager() { return manager; };
template <typename T> bool hasComponent() const template <typename T> bool hasComponent() const
{ {
@ -63,4 +93,5 @@ private:
ComponentArray componentArray = {}; ComponentArray componentArray = {};
ComponentBitSet componentBitSet; ComponentBitSet componentBitSet;
GroupBitSet groupBitSet; GroupBitSet groupBitSet;
TeamLabel teamLabel;
}; };

View File

@ -8,7 +8,8 @@
#include "Vector2D.h" #include "Vector2D.h"
class AssetManager; class AssetManager;
class ColliderComponent; class CollisionHandler;
enum class TeamLabel;
class Game class Game
{ {
@ -25,19 +26,18 @@ public:
void clean(); void clean();
bool running() const; bool running() const;
static void addTile(int id, int x, int y); static void addTile(unsigned long id, int x, int y);
static SDL_Renderer* renderer; static SDL_Renderer* renderer;
static SDL_Event event; static SDL_Event event;
static std::vector<ColliderComponent*> colliders; static CollisionHandler* collisionHandler;
static AssetManager* assets; static AssetManager* assets;
bool getWinner();
private: private:
void setWinner(TeamLabel winningTeam);
TeamLabel getWinner();
int counter = 0; int counter = 0;
bool isRunning = false; bool isRunning = false;
SDL_Window* window; SDL_Window* window;
TeamLabel winner;
//true for player1 win / false for player2 win;
bool winner;
}; };

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "Direction.h"
#include "Component.h" #include "Component.h"
class Manager; class Manager;
@ -8,22 +9,19 @@ class HealthComponent : public Component
{ {
public: public:
HealthComponent(int health, Manager* manager, bool player) : health(health), manager(manager), player(player) {} HealthComponent(int health, Direction side) : health(health), side(side) {}
~HealthComponent() {} ~HealthComponent() {}
void getDamage() { this->health--; } void modifyHealth(int health = -1);
int getHealth() { return this->health; } int getHealth() { return this->health; }
void init() override; void init() override;
void createAllHearts(); void refreshHearts();
void createHeartComponents(int x); void createHeartComponents(int x);
private: private:
int health; int health;
Manager* manager; Direction side;
bool player; //true if player1 / false if player2
}; };

View File

@ -5,8 +5,7 @@
#include <vector> #include <vector>
#include "Constants.h" #include "Constants.h"
#include "Entity.h"
class Entity;
class Manager class Manager
{ {
@ -18,9 +17,15 @@ public:
void addToGroup(Entity* mEntity, Group mGroup); void addToGroup(Entity* mEntity, Group mGroup);
std::vector<Entity*>& getGroup(Group mGroup); std::vector<Entity*>& getGroup(Group mGroup);
void addToTeam(Entity* mEntity, Team mTeam);
std::vector<Entity*>& getTeam(Team mTeam);
std::vector<Entity*> getAll();
Entity& addEntity(); Entity& addEntity();
private: private:
std::vector<std::unique_ptr<Entity>> entities; std::vector<std::unique_ptr<Entity>> entities;
std::array<std::vector<Entity*>, MAX_GROUPS> groupedEntities; std::array<std::vector<Entity*>, MAX_GROUPS> entitiesByGroup;
std::array<std::vector<Entity*>, MAX_TEAMS> entitiesByTeam;
}; };

View File

@ -0,0 +1,9 @@
#pragma once
#include "Component.h"
class PlayerComponent : public Component
{
public:
private:
};

View File

@ -10,14 +10,12 @@ class ProjectileComponent : public Component
//can maybe be split in separate .cpp file //can maybe be split in separate .cpp file
public: public:
ProjectileComponent(int range, int speed, Vector2D velocity, bool source) : range(range), speed(speed), velocity(velocity), source(source) {} ProjectileComponent(int range, int speed, Vector2D direction) : range(range), speed(speed), direction(direction) {}
~ProjectileComponent() {} ~ProjectileComponent() {}
void init() override; void init() override;
void update() override; void update() override;
bool getSource() { return this->source; }
private: private:
TransformComponent* transformComponent; TransformComponent* transformComponent;
@ -25,7 +23,5 @@ private:
int speed = 0; int speed = 0;
int distance = 0; int distance = 0;
const bool source; //true if from player1 / false if from player2 Vector2D direction;
Vector2D velocity;
}; };

View File

@ -5,15 +5,10 @@
#include "AnimationHandler.h" #include "AnimationHandler.h"
#include "Component.h" #include "Component.h"
#include "Direction.h"
class TransformComponent; class TransformComponent;
enum SpriteDirection
{
LEFT,
RIGHT
};
class SpriteComponent : public Component class SpriteComponent : public Component
{ {
public: public:
@ -43,5 +38,5 @@ public:
void update() override; void update() override;
void draw() override; void draw() override;
void playAnimation(AnimationType type); void playAnimation(AnimationType type);
void setDirection(SpriteDirection direction); void setDirection(Direction direction);
}; };

View File

@ -7,7 +7,7 @@ class TransformComponent : public Component
{ {
public: public:
Vector2D position; Vector2D position;
Vector2D velocity; Vector2D direction;
int height = 32; int height = 32;
int width = 32; int width = 32;

View File

@ -1,5 +1,8 @@
#pragma once #pragma once
#include <SDL.h>
#include <SDL_rect.h>
class Vector2D class Vector2D
{ {
public: public:
@ -13,7 +16,10 @@ public:
friend Vector2D& operator-(Vector2D& vector1, const Vector2D& vector2); friend Vector2D& operator-(Vector2D& vector1, const Vector2D& vector2);
friend Vector2D& operator*(Vector2D& vector1, const Vector2D& vector2); friend Vector2D& operator*(Vector2D& vector1, const Vector2D& vector2);
friend Vector2D& operator/(Vector2D& vector1, const Vector2D& vector2); friend Vector2D& operator/(Vector2D& vector1, const Vector2D& vector2);
friend Vector2D& operator+=(Vector2D& vector1, const Vector2D& vector2);
Vector2D& operator*(const int& i); Vector2D& operator*(const int& i);
Vector2D& zero(); Vector2D& zero();
}; };
SDL_Rect operator+(const SDL_Rect& rect, const Vector2D& vector2D);

View File

@ -1,5 +1,6 @@
#include "AssetManager.h" #include "AssetManager.h"
#include "Entity.h"
#include "TextureManager.h" #include "TextureManager.h"
#include "SoundManager.h" #include "SoundManager.h"
#include "Components.h" #include "Components.h"
@ -25,12 +26,13 @@ Mix_Chunk* AssetManager::getSound(std::string id) {
return soundEffects.at(id); return soundEffects.at(id);
} }
void AssetManager::createProjectile(Vector2D pos, Vector2D velocity, bool source, int scale, int range, int speed, const char* texturePath) { void AssetManager::createProjectile(Vector2D pos, Vector2D velocity, int scale, int range, int speed, const char* texturePath, TeamLabel teamLabel) {
auto& projectile(man->addEntity()); auto& projectile(man->addEntity());
projectile.addComponent<TransformComponent>(pos.x, pos.y, 32, 32, scale); //32x32 is standard size for objects projectile.addComponent<TransformComponent>(pos.x, pos.y, 32, 32, scale); //32x32 is standard size for objects
projectile.addComponent<SpriteComponent>(texturePath); projectile.addComponent<SpriteComponent>(texturePath);
projectile.addComponent<ProjectileComponent>(range, speed, velocity, source); projectile.addComponent<ProjectileComponent>(range, speed, velocity);
projectile.addComponent<ColliderComponent>("projectile", 0.6f); projectile.addComponent<ColliderComponent>("projectile", 0.6f);
projectile.addGroup((size_t)GroupLabel::PROJECTILE); projectile.addGroup((size_t)GroupLabel::PROJECTILE);
projectile.setTeam(teamLabel);
} }

View File

@ -1,5 +1,6 @@
#include "ColliderComponent.h" #include "ColliderComponent.h"
#include "CollisionHandler.h"
#include "Entity.h" #include "Entity.h"
#include "Game.h" #include "Game.h"
#include "TransformComponent.h" #include "TransformComponent.h"
@ -30,13 +31,14 @@ void ColliderComponent::init()
} }
transform = &entity->getComponent<TransformComponent>(); transform = &entity->getComponent<TransformComponent>();
Game::colliders.push_back(this); //Game::collisionHandler->add(this);
this->update();
} }
void ColliderComponent::update() void ColliderComponent::update()
{ {
collider.x = transform->position.x; collider.x = transform->position.x - (transform->width - transform->width * transform->scale * this->hitboxScale) / 2;
collider.y = transform->position.y; collider.y = transform->position.y - (transform->width - transform->width * transform->scale * this->hitboxScale) / 2;
collider.w = (transform->width * transform->scale) * this->hitboxScale; collider.w = (transform->width * transform->scale) * this->hitboxScale;

148
src/CollisionHandler.cpp Normal file
View File

@ -0,0 +1,148 @@
#include "CollisionHandler.h"
#include "ColliderComponent.h"
#include "Constants.h"
#include "Entity.h"
#include "Manager.h"
#include "Vector2D.h"
#include <SDL_rect.h>
#include <bitset>
#include <cstdio>
#include <memory>
IntersectionBitSet CollisionHandler::getIntersection(Entity* entityA, Entity* entityB, Vector2D posModA, Vector2D posModB)
{
if (!entityA->hasComponent<ColliderComponent>() ||
!entityB->hasComponent<ColliderComponent>())
return std::bitset<DIRECTION_C>();
SDL_Rect colliderA = entityA->getComponent<ColliderComponent>().collider;
SDL_Rect colliderB = entityB->getComponent<ColliderComponent>().collider;
colliderA.x += posModA.x;
colliderA.y += posModA.y;
colliderB.x += posModB.x;
colliderB.y += posModB.y;
if (!SDL_HasIntersection(
&colliderA,
&colliderB))
return std::bitset<DIRECTION_C>();
std::bitset<DIRECTION_C> intersections;
// checks all 4 directions to allow checking full overlap
if (colliderA.x < colliderB.x + colliderB.w &&
colliderA.x > colliderB.x) {
intersections.set((size_t) direction::LEFT);
}
if (colliderA.x + colliderA.w < colliderB.x + colliderB.w &&
colliderA.x + colliderA.w > colliderB.x) {
intersections.set((size_t) direction::RIGHT);
}
if (colliderA.y < colliderB.y + colliderB.h &&
colliderA.y > colliderB.y)
intersections.set((size_t) direction::UP);
if (colliderA.y + colliderA.h < colliderB.y + colliderB.h &&
colliderA.y + colliderA.h > colliderB.y)
intersections.set((size_t) direction::DOWN);
return intersections;
}
IntersectionBitSet CollisionHandler::getIntersectionWithBounds(Entity* entity, Vector2D posMod)
{
if (!entity->hasComponent<ColliderComponent>())
return std::bitset<DIRECTION_C>();
SDL_Rect* collider = &entity->getComponent<ColliderComponent>().collider;
std::bitset<DIRECTION_C> intersections;
// all 4 directions and both sides to allow checking for fully out of bounds
if (collider->x + posMod.x < 0 ||
collider->x + posMod.x > SCREEN_SIZE_WIDTH) {
intersections.set((size_t) direction::LEFT);
}
if (collider->x + collider->w + posMod.x < 0 ||
collider->x + collider->w + posMod.x > SCREEN_SIZE_WIDTH)
intersections.set((size_t) direction::RIGHT);
if (collider->y + posMod.y < 0 ||
collider->y + posMod.y > SCREEN_SIZE_HEIGHT)
intersections.set((size_t) direction::UP);
if (collider->y + collider->h + posMod.y < 0 ||
collider->y + collider->h + posMod.y > SCREEN_SIZE_HEIGHT)
intersections.set((size_t) direction::DOWN);
return intersections;
}
std::vector<ColliderComponent*> CollisionHandler::getColliders(
std::initializer_list<GroupLabel> const& groupLabels,
std::initializer_list<TeamLabel> const& teamLabels,
bool negateTeam)
{
std::vector<ColliderComponent*> colliders;
std::bitset<MAX_GROUPS> groupBitSet;
for (auto& groupLabel : groupLabels) {
groupBitSet.set((size_t) groupLabel);
}
std::bitset<MAX_TEAMS> teamBitSet;
for (auto& teamLabel : teamLabels) {
teamBitSet.set((size_t) teamLabel);
}
for (auto& entity : manager.getAll()) {
if ((groupBitSet & entity->getGroupBitSet()).none())
continue;
if (teamBitSet.any() && negateTeam != (teamBitSet.test((size_t) entity->getTeam())))
continue;
if (!entity->hasComponent<ColliderComponent>())
continue;
colliders.emplace_back(&entity->getComponent<ColliderComponent>());
}
return colliders;
}
template<>
IntersectionBitSet CollisionHandler::getAnyIntersection<IntersectionBitSet>(
Entity* entity,
Vector2D posMod,
std::initializer_list<GroupLabel> const& groupLabels,
std::initializer_list<TeamLabel> const& teamLabels,
bool negateTeam)
{
IntersectionBitSet intersections;
for (auto& collider : getColliders(groupLabels, teamLabels)) {
intersections |= getIntersection(entity, collider->entity, posMod);
}
return intersections;
};
template<>
Entity* CollisionHandler::getAnyIntersection<Entity*>(
Entity* entity,
Vector2D posMod,
std::initializer_list<GroupLabel> const& groupLabels,
std::initializer_list<TeamLabel> const& teamLabels,
bool negateTeam)
{
for (auto& collider : getColliders(groupLabels, teamLabels)) {
SDL_Rect rect = entity->getComponent<ColliderComponent>().collider + posMod;
if (SDL_HasIntersection(&rect, &collider->collider)) {
return collider->entity;
}
}
return nullptr;
};

View File

@ -2,6 +2,7 @@
#include "Manager.h" #include "Manager.h"
#include "Component.h" #include "Component.h"
#include <cstddef>
void Entity::update() const void Entity::update() const
{ {
@ -28,3 +29,19 @@ void Entity::delGroup(Group mGroup)
{ {
groupBitSet[mGroup] = false; groupBitSet[mGroup] = false;
} }
std::bitset<MAX_GROUPS> Entity::getGroupBitSet()
{
return groupBitSet;
}
void Entity::setTeam(TeamLabel teamLabel)
{
this->teamLabel = teamLabel;
manager.addToTeam(this, (size_t) teamLabel);
}
TeamLabel Entity::getTeam()
{
return teamLabel;
}

View File

@ -2,8 +2,12 @@
#include <SDL_error.h> #include <SDL_error.h>
#include "CollisionHandler.h"
#include "Components.h" #include "Components.h"
#include "AssetManager.h" #include "AssetManager.h"
#include "Direction.h"
#include "Entity.h"
#include "HealthComponent.h"
#include "Map.h" #include "Map.h"
#include "TextureManager.h" #include "TextureManager.h"
#include "Constants.h" #include "Constants.h"
@ -13,14 +17,15 @@ Manager manager;
AssetManager* Game::assets = new AssetManager(&manager); AssetManager* Game::assets = new AssetManager(&manager);
CollisionHandler* Game::collisionHandler = new CollisionHandler(manager);
SDL_Renderer* Game::renderer = nullptr; SDL_Renderer* Game::renderer = nullptr;
SDL_Event Game::event; SDL_Event Game::event;
std::vector<ColliderComponent*> Game::colliders; auto& player1(manager.addEntity());
auto& player2(manager.addEntity());
auto& player(manager.addEntity());
auto& enemy(manager.addEntity());
auto& wall(manager.addEntity()); auto& wall(manager.addEntity());
//auto& projectile (manager.addEntity()); //auto& projectile (manager.addEntity());
@ -134,19 +139,23 @@ void Game::init(const char* title, int xpos, int ypos, int width, int height, bo
//ecs implementation //ecs implementation
player.addComponent<TransformComponent>(80,80,2); //posx, posy, scale
player.addComponent<SpriteComponent>(playerSprite, true); //adds sprite (32x32px), path needed
player.addComponent<KeyboardController>(SDL_SCANCODE_W, SDL_SCANCODE_S, SDL_SCANCODE_A, SDL_SCANCODE_D, SDL_SCANCODE_E, Vector2D(1, 0));//custom keycontrols can be added
player.addComponent<ColliderComponent>("player", 0.8f); //adds tag (for further use, reference tag)
player.addComponent<HealthComponent>(5, &manager, true);
player.addGroup((size_t)GroupLabel::PLAYERS); //tell programm what group it belongs to for rendering order
enemy.addComponent<TransformComponent>(600, 500, 2); player1.setTeam(TeamLabel::BLUE);
enemy.addComponent<SpriteComponent>(enemySprite, true); player1.addComponent<TransformComponent>(80,80,2); //posx, posy, scale
enemy.addComponent<KeyboardController>(SDL_SCANCODE_UP, SDL_SCANCODE_DOWN, SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT, SDL_SCANCODE_RCTRL, Vector2D(-1, 0)); player1.addComponent<SpriteComponent>("assets/chicken_knight_spritesheet.png", true); //adds sprite (32x32px), path needed
enemy.addComponent<ColliderComponent>("enemy", 0.8f); player1.addComponent<KeyboardController>(SDL_SCANCODE_W, SDL_SCANCODE_S, SDL_SCANCODE_A, SDL_SCANCODE_D, SDL_SCANCODE_E, Vector2D(1, 0));//custom keycontrols can be added
enemy.addComponent<HealthComponent>(5, &manager, false); player1.addComponent<ColliderComponent>("player", 0.8f); //adds tag (for further use, reference tag)
enemy.addGroup((size_t)GroupLabel::ENEMIES); player1.addComponent<HealthComponent>(5, Direction::LEFT);
player1.addGroup((size_t) GroupLabel::PLAYERS); //tell programm what group it belongs to for rendering order
player2.setTeam(TeamLabel::RED);
player2.addComponent<TransformComponent>(600, 500, 2);
player2.addComponent<SpriteComponent>("assets/chicken_spritesheet.png", true);
player2.addComponent<KeyboardController>(SDL_SCANCODE_UP, SDL_SCANCODE_DOWN, SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT, SDL_SCANCODE_RCTRL, Vector2D(-1, 0));
player2.addComponent<ColliderComponent>("enemy", 0.8f);
player2.addComponent<HealthComponent>(5, Direction::RIGHT);
player2.addGroup((size_t) GroupLabel::PLAYERS);
} }
@ -246,9 +255,8 @@ void Game::selectCharacters(const char* &playerSprite, const char* &enemySprite)
this->isRunning = true; this->isRunning = true;
} }
auto& tiles(manager.getGroup((size_t)GroupLabel::MAP)); auto& tiles(manager.getGroup((size_t)GroupLabel::MAPTILES));
auto& players(manager.getGroup((size_t)GroupLabel::PLAYERS)); auto& players(manager.getGroup((size_t)GroupLabel::PLAYERS));
auto& enemies(manager.getGroup((size_t)GroupLabel::ENEMIES));
auto& projectiles(manager.getGroup((size_t)GroupLabel::PROJECTILE)); auto& projectiles(manager.getGroup((size_t)GroupLabel::PROJECTILE));
auto& hearts(manager.getGroup((size_t)GroupLabel::HEARTS)); auto& hearts(manager.getGroup((size_t)GroupLabel::HEARTS));
@ -268,82 +276,16 @@ void Game::handleEvents()
void Game::update() void Game::update()
{ {
Vector2D playerPos = player.getComponent<TransformComponent>().position; Vector2D playerPos = player1.getComponent<TransformComponent>().position;
Vector2D enemyPos = enemy.getComponent<TransformComponent>().position; Vector2D enemyPos = player2.getComponent<TransformComponent>().position;
manager.refresh(); manager.refresh();
manager.update(); manager.update();
for (auto cc : colliders) // needs to be in game.cpp to have access to internal functions
{ for (auto& player : manager.getGroup((size_t) GroupLabel::PLAYERS)) {
if (SDL_HasIntersection(&player.getComponent<ColliderComponent>().collider, &cc->collider) && strcmp(cc->tag, "player") && cc->hasCollision) if (player->getComponent<HealthComponent>().getHealth() <= 0) {
{ this->setWinner(player->getTeam());
if (!cc->isProjectile)
{
player.getComponent<ColliderComponent>().handleCollision(player.getComponent<TransformComponent>().position, player.getComponent<ColliderComponent>().collider, cc->collider);
}
else
{
player.getComponent<TransformComponent>().position = playerPos;
}
}
if (SDL_HasIntersection(&enemy.getComponent<ColliderComponent>().collider, &cc->collider) && strcmp(cc->tag, "enemy") && cc->hasCollision)
{
if (!cc->isProjectile)
{
enemy.getComponent<ColliderComponent>().handleCollision(enemy.getComponent<TransformComponent>().position, enemy.getComponent<ColliderComponent>().collider, cc->collider);
}
else
{
enemy.getComponent<TransformComponent>().position = enemyPos;
}
}
}
//checking if projectiles hit player1 or player2
for (auto& p : projectiles) {
if(SDL_HasIntersection(&enemy.getComponent<ColliderComponent>().collider, &p->getComponent<ColliderComponent>().collider)
&& (p->getComponent<ColliderComponent>().hasCollision) && !p->getComponent<ProjectileComponent>().getSource()) {
//std::cout << "Enemy hit!";
p->getComponent<ColliderComponent>().removeCollision();
p->destroy();
enemy.getComponent<HealthComponent>().getDamage();
//display updated health | pretty scuffed but works ig
for(auto h : hearts)
h->destroy();
player.getComponent<HealthComponent>().createAllHearts();
enemy.getComponent<HealthComponent>().createAllHearts();
if(enemy.getComponent<HealthComponent>().getHealth() < 1) {
std::cout << "Player1 wins!" << std::endl;
winner = true;
isRunning = false;
}
}
if(SDL_HasIntersection(&player.getComponent<ColliderComponent>().collider, &p->getComponent<ColliderComponent>().collider)
&& (p->getComponent<ColliderComponent>().hasCollision) && p->getComponent<ProjectileComponent>().getSource()) {
//std::cout << "Player hit!";
p->getComponent<ColliderComponent>().removeCollision();
p->destroy();
player.getComponent<HealthComponent>().getDamage();
//display updated health
for(auto h : hearts)
h->destroy();
player.getComponent<HealthComponent>().createAllHearts();
enemy.getComponent<HealthComponent>().createAllHearts();
if(player.getComponent<HealthComponent>().getHealth() < 1) {
std::cout << "Player2 wins!" << std::endl;
winner = false;
isRunning = false;
}
} }
} }
} }
@ -359,10 +301,6 @@ void Game::render()
{ {
p->draw(); p->draw();
} }
for (auto& e : enemies)
{
e->draw();
}
for (auto& p : projectiles) for (auto& p : projectiles)
p->draw(); p->draw();
@ -380,12 +318,12 @@ void Game::clean()
std::cout << "Game Cleaned!" << std::endl; std::cout << "Game Cleaned!" << std::endl;
} }
void Game::addTile(int id, int x, int y) void Game::addTile(unsigned long id, int x, int y)
{ {
auto& tile(manager.addEntity()); auto& tile(manager.addEntity());
tile.addComponent<TileComponent>(x, y, TILE_SIZE, TILE_SIZE, id); tile.addComponent<TileComponent>(x, y, TILE_SIZE, TILE_SIZE, id);
if (id == 1) tile.addComponent<ColliderComponent>("water"); if (id == 1) tile.addComponent<ColliderComponent>("water");
tile.addGroup((size_t)GroupLabel::MAP); tile.addGroup((size_t)GroupLabel::MAPTILES);
} }
bool Game::running() const bool Game::running() const
@ -393,6 +331,13 @@ bool Game::running() const
return isRunning; return isRunning;
} }
bool Game::getWinner() { void Game::setWinner(TeamLabel winningTeam)
{
this->winner = winningTeam;
this->isRunning = false;
}
TeamLabel Game::getWinner()
{
return this->winner; return this->winner;
} }

View File

@ -1,17 +1,34 @@
#include "HealthComponent.h" #include "HealthComponent.h"
#include "Components.h" #include "Components.h"
#include "Direction.h"
#include "Entity.h"
#include "Game.h"
#include <cstdio>
void HealthComponent::init() void HealthComponent::init()
{ {
createAllHearts(); refreshHearts();
} }
void HealthComponent::createAllHearts() void HealthComponent::modifyHealth(int health)
{ {
this->health += health;
this->refreshHearts();
}
void HealthComponent::refreshHearts()
{
// clear hearts if exist
for (auto& heart : this->entity->getManager().getGroup((size_t) GroupLabel::HEARTS)) {
if (heart->getTeam() == this->entity->getTeam()) {
heart->destroy();
}
}
int x; //starting position for first health icon int x; //starting position for first health icon
if(player) { if(side == Direction::LEFT) {
x = 10; x = 10;
} else { } else {
x = 730; x = 730;
@ -20,7 +37,7 @@ void HealthComponent::createAllHearts()
for(int i = 0; i < health; i++) { for(int i = 0; i < health; i++) {
//checks for player side //checks for player side
if(player) { if (side == Direction::LEFT) {
createHeartComponents(x); createHeartComponents(x);
x += 50; x += 50;
continue; continue;
@ -33,8 +50,9 @@ void HealthComponent::createAllHearts()
void HealthComponent::createHeartComponents(int x) void HealthComponent::createHeartComponents(int x)
{ {
auto& heart(manager->addEntity()); auto& heart(this->entity->getManager().addEntity());
heart.addComponent<TransformComponent>(x,5,2); heart.addComponent<TransformComponent>(x,5,2);
heart.addComponent<SpriteComponent>("assets/heart.png"); heart.addComponent<SpriteComponent>("assets/heart.png");
heart.addGroup((size_t)GroupLabel::HEARTS); heart.addGroup((size_t)GroupLabel::HEARTS);
heart.setTeam(this->entity->getTeam());
} }

View File

@ -23,30 +23,30 @@ void KeyboardController::init()
void KeyboardController::update() void KeyboardController::update()
{ {
transform->velocity.x = 0; transform->direction.x = 0;
transform->velocity.y = 0; transform->direction.y = 0;
sprite->playAnimation(IDLE); sprite->playAnimation(IDLE);
if (keystates[this->up]) { if (keystates[this->up]) {
transform->velocity.y = -1; transform->direction.y = -1;
sprite->playAnimation(WALK); sprite->playAnimation(WALK);
SoundManager::playSound(STEPS); SoundManager::playSound(STEPS);
} }
if (keystates[this->left]) { if (keystates[this->left]) {
transform->velocity.x = -1; transform->direction.x = -1;
sprite->playAnimation(WALK); sprite->playAnimation(WALK);
sprite->setDirection(LEFT); sprite->setDirection(Direction::LEFT);
SoundManager::playSound(STEPS); SoundManager::playSound(STEPS);
} }
if (keystates[this->down]) { if (keystates[this->down]) {
transform->velocity.y = 1; transform->direction.y = 1;
sprite->playAnimation(WALK); sprite->playAnimation(WALK);
SoundManager::playSound(STEPS); SoundManager::playSound(STEPS);
} }
if (keystates[this->right]) { if (keystates[this->right]) {
transform->velocity.x = 1; transform->direction.x = 1;
sprite->playAnimation(WALK); sprite->playAnimation(WALK);
sprite->setDirection(RIGHT); sprite->setDirection(Direction::RIGHT);
SoundManager::playSound(STEPS); SoundManager::playSound(STEPS);
} }
@ -61,14 +61,14 @@ void KeyboardController::update()
//checks player source via the firing velocity //checks player source via the firing velocity
//TODO: adding actual projectile textures //TODO: adding actual projectile textures
if (fireVelocity.x > 0) { if (fireVelocity.x > 0) {
sprite->setDirection(RIGHT); sprite->setDirection(Direction::RIGHT);
Game::assets->createProjectile(Vector2D(player->position.x, player->position.y), fireVelocity, Game::assets->createProjectile(Vector2D(player->position.x, player->position.y), fireVelocity,
false, 1, 180, 1, "assets/egg.png"); 1, 180, 1, "assets/egg.png", this->entity->getTeam());
} }
else { else {
sprite->setDirection(LEFT); sprite->setDirection(Direction::LEFT);
Game::assets->createProjectile(Vector2D(player->position.x, player->position.y), fireVelocity, Game::assets->createProjectile(Vector2D(player->position.x, player->position.y), fireVelocity,
true, 1, 180, 1, "assets/egg.png"); 1, 180, 1, "assets/egg.png", this->entity->getTeam());
} }
lastFireTime = currentTicks; lastFireTime = currentTicks;

View File

@ -1,14 +1,11 @@
#include "Manager.h" #include "Manager.h"
#include <algorithm> #include <algorithm>
#include <vector>
#include "Constants.h"
#include "Entity.h" #include "Entity.h"
void Manager::update()
{
for (auto& e : entities) e->update();
}
void Manager::draw() void Manager::draw()
{ {
for (auto& e : entities) e->draw(); for (auto& e : entities) e->draw();
@ -18,7 +15,7 @@ void Manager::refresh()
{ {
for (auto i(0u); i < MAX_GROUPS; i++) for (auto i(0u); i < MAX_GROUPS; i++)
{ {
auto& v(groupedEntities[i]); auto& v(entitiesByGroup[i]);
v.erase( v.erase(
std::remove_if(std::begin(v), std::end(v), std::remove_if(std::begin(v), std::end(v),
[i](Entity* mEntity) [i](Entity* mEntity)
@ -27,6 +24,17 @@ void Manager::refresh()
}), std::end(v)); }), std::end(v));
} }
for (auto i(0u); i < MAX_TEAMS; i++)
{
auto& v(entitiesByTeam[i]);
v.erase(
std::remove_if(std::begin(v), std::end(v),
[i](Entity* mEntity)
{
return !mEntity->isActive() || (size_t)(mEntity->getTeam()) != i;
}), std::end(v));
}
entities.erase(std::remove_if(std::begin(entities), std::end(entities), entities.erase(std::remove_if(std::begin(entities), std::end(entities),
[](const std::unique_ptr<Entity>& mEntity) [](const std::unique_ptr<Entity>& mEntity)
{ {
@ -35,14 +43,38 @@ void Manager::refresh()
std::end(entities)); std::end(entities));
} }
void Manager::update()
{
for (auto& e : entities) e->update();
}
void Manager::addToGroup(Entity* mEntity, Group mGroup) void Manager::addToGroup(Entity* mEntity, Group mGroup)
{ {
groupedEntities[mGroup].emplace_back(mEntity); entitiesByGroup.at(mGroup).emplace_back(mEntity);
} }
std::vector<Entity*>& Manager::getGroup(Group mGroup) std::vector<Entity*>& Manager::getGroup(Group mGroup)
{ {
return groupedEntities[mGroup]; return entitiesByGroup.at(mGroup);
}
void Manager::addToTeam(Entity* mEntity, Team mTeam)
{
entitiesByTeam.at(mTeam).emplace_back(mEntity); //
}
std::vector<Entity*>& Manager::getTeam(Team mTeam)
{
return entitiesByTeam.at(mTeam);
}
std::vector<Entity*> Manager::getAll()
{
std::vector<Entity*> entity_vec;
for (auto& entity_ptr : entities) {
entity_vec.emplace_back(entity_ptr.get());
}
return entity_vec;
} }
Entity& Manager::addEntity() Entity& Manager::addEntity()

1
src/PlayerComponent.cpp Normal file
View File

@ -0,0 +1 @@
#include "PlayerComponent.h"

View File

@ -1,22 +1,45 @@
#include "ProjectileComponent.h" #include "ProjectileComponent.h"
#include "CollisionHandler.h"
#include "Components.h" #include "Components.h"
#include "Entity.h"
#include "Game.h"
#include "HealthComponent.h"
#include "Vector2D.h"
#include <cassert>
#include <cstdio>
void ProjectileComponent::init() void ProjectileComponent::init()
{ {
transformComponent = &entity->getComponent<TransformComponent>(); transformComponent = &entity->getComponent<TransformComponent>();
transformComponent->direction = direction;
SoundManager::playSound(THROW_EGG); SoundManager::playSound(THROW_EGG);
} }
void ProjectileComponent::update() void ProjectileComponent::update()
{ {
transformComponent->velocity = velocity;
distance += speed; distance += speed;
IntersectionBitSet boundsIntersection = Game::collisionHandler->getIntersectionWithBounds(entity);
if ((boundsIntersection | IntersectionBitSet("1100")).all() || (boundsIntersection | IntersectionBitSet("0011")).all()) {
this->entity->destroy();
std::cout << "out of bounds" << std::endl;
}
if (distance > range) { if (distance > range) {
entity->destroy(); this->entity->destroy();
entity->getComponent<ColliderComponent>().removeCollision(); std::cout << "out of range" << std::endl;
//std::cout << "out of range" << std::endl; }
Entity* player;
if ((player = Game::collisionHandler->getAnyIntersection<Entity*>(
entity,
Vector2D(0,0),
{GroupLabel::PLAYERS},
{entity->getTeam()},
true)) != nullptr) {
player->getComponent<HealthComponent>().modifyHealth();
this->entity->destroy();
} }
} }

View File

@ -2,6 +2,7 @@
#include <SDL_timer.h> #include <SDL_timer.h>
#include "Direction.h"
#include "TextureManager.h" #include "TextureManager.h"
#include "Entity.h" #include "Entity.h"
#include "TransformComponent.h" #include "TransformComponent.h"
@ -71,9 +72,9 @@ void SpriteComponent::playAnimation(AnimationType type)
this->speed = animations.at(type)->speed; this->speed = animations.at(type)->speed;
} }
void SpriteComponent::setDirection(SpriteDirection direction) void SpriteComponent::setDirection(Direction direction)
{ {
if (direction == RIGHT) { if (direction == Direction::RIGHT) {
this->flipped = true; this->flipped = true;
return; return;
} }

View File

@ -1,5 +1,14 @@
#include "TransformComponent.h" #include "TransformComponent.h"
#include "CollisionHandler.h"
#include "ColliderComponent.h"
#include "Constants.h" #include "Constants.h"
#include "Entity.h"
#include "Game.h"
#include "Vector2D.h"
#include <cstdio>
#include <initializer_list>
#include <iostream>
#include "SoundManager.h" #include "SoundManager.h"
@ -38,37 +47,36 @@ TransformComponent::TransformComponent(float x, float y, int w, int h, int scale
void TransformComponent::init() void TransformComponent::init()
{ {
velocity.zero(); direction.zero();
} }
void TransformComponent::update() void TransformComponent::update()
{ {
// if(velocity.x != 0 && velocity.y != 0) // if(velocity.x != 0 && velocity.y != 0)
float multiplier = velocity.x != 0 && velocity.y != 0 ? 0.707 : 1; //normalizes vector float multiplier = direction.x != 0 && direction.y != 0 ? 0.707 : 1; // normalizes vector; only works if directions are in increments of 45°
Vector2D positionChange(
Vector2D newPos( direction.x * speed * multiplier,
position.x + velocity.x * speed * multiplier, direction.y * speed * multiplier
position.y + velocity.y * speed * multiplier
); );
if (newPos.x < 0) // TODO: move to separate functions
{
newPos.x = 0; if (this->entity->hasGroup((size_t) GroupLabel::PLAYERS)) {
} IntersectionBitSet intersections =
else if (newPos.x + (this->width * this->scale) > SCREEN_SIZE_WIDTH) (CollisionHandler::getIntersectionWithBounds(entity, Vector2D(positionChange.x, 0)) |
{ (Game::collisionHandler->getAnyIntersection<IntersectionBitSet>(entity, Vector2D(positionChange.x, 0), {GroupLabel::MAPTILES, GroupLabel::COLLIDERS})) &
newPos.x = SCREEN_SIZE_WIDTH - (this->width * this->scale); IntersectionBitSet("0011")) |
(CollisionHandler::getIntersectionWithBounds(entity, Vector2D(0, positionChange.y)) |
(Game::collisionHandler->getAnyIntersection<IntersectionBitSet>(entity, Vector2D(0, positionChange.y), {GroupLabel::MAPTILES, GroupLabel::COLLIDERS})) &
IntersectionBitSet("1100"));
if (intersections.test((size_t) direction::LEFT) || intersections.test((size_t) direction::RIGHT))
positionChange.x = 0;
if (intersections.test((size_t) direction::UP) || intersections.test((size_t) direction::DOWN))
positionChange.y = 0;
} }
if (newPos.y < 0) position += positionChange;
{ };
newPos.y = 0;
}
else if (newPos.y + (this->height * this->scale) > SCREEN_SIZE_HEIGHT)
{
newPos.y = SCREEN_SIZE_HEIGHT - (this->height * this->scale);
}
position = newPos;
}

View File

@ -1,4 +1,5 @@
#include "Vector2D.h" #include "Vector2D.h"
#include "SDL_rect.h"
Vector2D::Vector2D() Vector2D::Vector2D()
{ {
@ -36,6 +37,12 @@ Vector2D& operator/(Vector2D& vector1, const Vector2D& vector2)
vector1.y /= vector2.y; vector1.y /= vector2.y;
return vector1; return vector1;
} }
Vector2D& operator+=(Vector2D& vector1, const Vector2D& vector2)
{
vector1.x += vector2.x;
vector1.y += vector2.y;
return vector1;
}
Vector2D& Vector2D::operator*(const int& i) Vector2D& Vector2D::operator*(const int& i)
{ {
this->x *= i; this->x *= i;
@ -50,3 +57,11 @@ Vector2D& Vector2D::zero()
return *this; return *this;
} }
SDL_Rect operator+(const SDL_Rect& rect, const Vector2D& vector2D)
{
SDL_Rect newRect = rect;
newRect.x += vector2D.x;
newRect.y += vector2D.y;
return newRect;
}