holesome/src/game/physics/map_simulation.cpp

72 lines
2.1 KiB
C++

#include "map_simulation.hpp"
#include "../../config.h"
MapSimulation::MapSimulation()
{
mapPlayersById = std::map<int, std::shared_ptr<MapPlayer>>();
}
std::shared_ptr<MapSimulation> MapSimulation::getInstance()
{
if (singletonInstance == nullptr)
{
singletonInstance = std::make_shared<MapSimulation>();
}
return singletonInstance;
}
void MapSimulation::updateSimulation()
{
// Update simulation positions
for (auto &mapPlayer: mapPlayersById)
{
mapPlayer.second->updateSimulationPosition();
}
world->Step(FRAME_TIME.asSeconds(), MAPSIM_VELOCITY_ITERATIONS, MAPSIM_POSITION_ITERATIONS);
// Update player positions
for (auto &mapPlayer: mapPlayersById)
{
mapPlayer.second->updatePlayerPosition();
}
}
void MapSimulation::resetMap(sf::Vector2f worldMapSize)
{
// No gravity, since this a top-down view of the map
world = std::make_shared<b2World>(b2Vec2(0.0f, 0.0f));
mapPlayersById.clear();
// Create map borders
constructSquareObstacle(-1, 0, 0, worldMapSize.y);
constructSquareObstacle(0, -1, worldMapSize.x, 0);
constructSquareObstacle(worldMapSize.x, 0, worldMapSize.x + 1, worldMapSize.y);
constructSquareObstacle(0, worldMapSize.y, worldMapSize.x, worldMapSize.y + 1);
}
void MapSimulation::constructSquareObstacle(float minX, float minY, float maxX, float maxY)
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((maxX + minX) / 2.f, (maxY + minY) / 2.f);
b2Body *body = world->CreateBody(&bodyDef);
b2PolygonShape shape;
shape.SetAsBox((maxX - minX) / 2.f, (maxY - minY) / 2.f);
b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 1.0f;
body->CreateFixture(&fixtureDef);
}
void MapSimulation::addPlayer(Player *player)
{
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(player->coordinates->world().x, player->coordinates->world().y);
b2Body *body = world->CreateBody(&bodyDef);
mapPlayersById[player->getPlayerId()] = std::make_shared<MapPlayer>(player, body);
}