[Add] Some pathfinding code.

This commit is contained in:
Tamir Atias 2012-02-20 21:59:51 +02:00
parent 8b92224e72
commit c8460abb90
13 changed files with 221 additions and 168 deletions

View File

@ -41,6 +41,7 @@ HEADERS += ../src/Libs/wglext.h \
../src/libUnuk/LevelGen/MapEntities.h \ ../src/libUnuk/LevelGen/MapEntities.h \
../src/libUnuk/LevelGen/MapElement.h \ ../src/libUnuk/LevelGen/MapElement.h \
../src/libUnuk/LevelGen/MapTile.h \ ../src/libUnuk/LevelGen/MapTile.h \
../src/libUnuk/LevelGen/AStarTile.h \
../src/libUnuk/UI/EventHistory.h \ ../src/libUnuk/UI/EventHistory.h \
../src/libUnuk/UI/Bar.h \ ../src/libUnuk/UI/Bar.h \
../src/libUnuk/System/Vec2.h \ ../src/libUnuk/System/Vec2.h \
@ -77,7 +78,7 @@ SOURCES += ../src/libUnuk/Engine/WorldManager.cpp \
../src/libUnuk/LevelGen/LevelGen.cpp \ ../src/libUnuk/LevelGen/LevelGen.cpp \
../src/libUnuk/LevelGen/MapEntities.cpp \ ../src/libUnuk/LevelGen/MapEntities.cpp \
../src/libUnuk/LevelGen/MapElement.cpp \ ../src/libUnuk/LevelGen/MapElement.cpp \
../src/libUnuk/LevelGen/MapTile.cpp \ ../src/libUnuk/LevelGen/AStarTile.cpp \
../src/libUnuk/UI/EventHistory.cpp \ ../src/libUnuk/UI/EventHistory.cpp \
../src/libUnuk/UI/Bar.cpp \ ../src/libUnuk/UI/Bar.cpp \
../src/libUnuk/System/Vec2.cpp \ ../src/libUnuk/System/Vec2.cpp \

View File

@ -208,6 +208,14 @@
<Filter <Filter
Name="LevelGen" Name="LevelGen"
> >
<File
RelativePath="..\..\..\src\libUnuk\LevelGen\AStarTile.cpp"
>
</File>
<File
RelativePath="..\..\..\src\libUnuk\LevelGen\AStarTile.h"
>
</File>
<File <File
RelativePath="..\..\..\src\libUnuk\LevelGen\LevelGen.cpp" RelativePath="..\..\..\src\libUnuk\LevelGen\LevelGen.cpp"
> >
@ -232,10 +240,6 @@
RelativePath="..\..\..\src\libUnuk\LevelGen\MapEntities.h" RelativePath="..\..\..\src\libUnuk\LevelGen\MapEntities.h"
> >
</File> </File>
<File
RelativePath="..\..\..\src\libUnuk\LevelGen\MapTile.cpp"
>
</File>
<File <File
RelativePath="..\..\..\src\libUnuk\LevelGen\MapTile.h" RelativePath="..\..\..\src\libUnuk\LevelGen\MapTile.h"
> >

View File

@ -15,6 +15,10 @@ Character::Character(LevelGen* mapArg) {
_leftFoot = false; _leftFoot = false;
_health = 100; _health = 100;
x = 0;
y = 0;
w = 40;
h = 45;
xVel = 0.0f; xVel = 0.0f;
yVel = 0.0f; yVel = 0.0f;

View File

@ -1,18 +1,21 @@
#include "NPC.h" #include "NPC.h"
#include "../Unuk/Player.h" #include "../../Unuk/Player.h"
#include "../System/Vec2.h"
NPC::NPC(LevelGen* mapArg) : Character(mapArg) { NPC::NPC(LevelGen* mapArg) : Character(mapArg) {
_moveTimer.Start(); _walkInPath = false;
_moving = false;
_moveChangeFrequency = 14000;
_moveDurationMax = 3000;
_moveDurationMin = 1000;
} }
NPC::~NPC(void) { NPC::~NPC(void) {
} }
void NPC::ForceMove(void) {
tileX = x / AStarTile::FAKE_SIZE;
tileY = y / AStarTile::FAKE_SIZE;
}
void NPC::Update(void) { void NPC::Update(void) {
// Store the NPC's health. // Store the NPC's health.
// int health = GetHealth(); // not referenced // int health = GetHealth(); // not referenced
@ -28,66 +31,83 @@ void NPC::Update(void) {
} }
void NPC::Move(void) { void NPC::Move(void) {
if(_moving && _moveTimer.GetTicks() > _moveDurationMax) { Vec2 realPos(x, y);
xVel = 0.0f; Vec2 tilePos(tileX, tileY);
yVel = 0.0f;
_moving = false;
}
if(_moving && _moveTimer.GetTicks() >= _moveDurationCurrent) { if(realPos != tilePos) {
xVel = 0.0f; float targetX = (float)(tileX * AStarTile::FAKE_SIZE);
yVel = 0.0f; float targetY = (float)(tileY * AStarTile::FAKE_SIZE);
_moving = false;
}
if(_moveTimer.GetTicks() > _moveChangeFrequency) { float dx = targetX - realPos.x;
_moveTimer.Start(); float dy = targetY - realPos.y;
_moveDurationCurrent = _moveDurationMin + (rand() % (_moveDurationMax - _moveDurationMin));
if(rand() % 2) { float distance = sqrtf(dx*dx + dy*dy);
yVel = 0.0f;
if(rand() % 2) if(fabs(distance) > CHARACTER_SPEED) {
xVel = CHARACTER_SPEED; dx /= distance;
else dy /= distance;
xVel = -CHARACTER_SPEED; dx *= CHARACTER_SPEED;
} else { dy *= CHARACTER_SPEED;
xVel = 0.0f;
if(rand() % 2) xVel = dx;
yVel = CHARACTER_SPEED; yVel = dy;
else
yVel = -CHARACTER_SPEED;
}
_moving = true;
}
map->MoveIfPossible(this, xVel, yVel, false); map->MoveIfPossible(this, xVel, yVel, false);
Character::HealthBarScroll(); Character::HealthBarScroll();
_moving = true;
} else {
xVel = 0.0f;
yVel = 0.0f;
_moving = false;
}
} else {
xVel = 0.0f;
yVel = 0.0f;
_moving = false;
}
if(_walkInPath && !_moving) {
Vec2 targetPos((float)_target->GetX(), (float)_target->GetY());
if(abs(Vec2::Distance(targetPos, realPos)) <= CHARACTER_SPEED) {
_target = _astar.GetSolutionNext();
if(_target == NULL || _target == _lastTarget) {
_walkInPath = false;
} else {
tileX = _target->GetX() / AStarTile::FAKE_SIZE;
tileY = _target->GetY() / AStarTile::FAKE_SIZE;
}
}
}
} }
void NPC::OnPlayerMove(Player* player) { void NPC::OnPlayerMove(Player* player) {
MapTile& start = map->GetTile(x / TILE_WIDTH, y / TILE_HEIGHT); AStarTile& start = map->GetAStarTile(x / AStarTile::FAKE_SIZE, y / AStarTile::FAKE_SIZE);
MapTile& goal = map->GetTile(player->GetX() / TILE_WIDTH, player->GetY() / TILE_HEIGHT); AStarTile& goal = map->GetAStarTile(player->GetX() / AStarTile::FAKE_SIZE, player->GetY() / AStarTile::FAKE_SIZE);
_astar.SetStartAndGoalStates(start, goal); _astar.SetStartAndGoalStates(start, goal);
bool solutionFound = false; _walkInPath = false;
// Dirty loop to calculate the path // Dirty loop to calculate the path
while(true) { while(true) {
_astar.SearchStep(); unsigned int state = _astar.SearchStep();
if(state == AStarSearch<AStarTile>::SEARCH_STATE_SUCCEEDED) {
int state = _astar.GetState(); _walkInPath = true;
if(state == AStarSearch<MapTile>::SEARCH_STATE_SUCCEEDED) {
solutionFound = true;
break; break;
} else if(state == AStarSearch<MapTile>::SEARCH_STATE_SEARCHING) { } else if(state != AStarSearch<AStarTile>::SEARCH_STATE_SEARCHING) {
continue; break;
}
}
_lastTarget = _astar.GetSolutionEnd();
_target = _astar.GetSolutionStart();
_target = _astar.GetSolutionNext();
if(!_target) {
_walkInPath = false;
} else { } else {
break; tileX = _target->GetX() / AStarTile::FAKE_SIZE;
} tileY = _target->GetY() / AStarTile::FAKE_SIZE;
}
if(solutionFound) {
x = _astar.GetSolutionEnd()->GetTileX();
y = _astar.GetSolutionEnd()->GetTileY();
} }
} }

View File

@ -2,7 +2,7 @@
#include "Character.h" #include "Character.h"
#include "Pathfinding.h" #include "Pathfinding.h"
#include "../LevelGen/MapTile.h" #include "../LevelGen/AStarTile.h"
class Player; class Player;
@ -11,6 +11,7 @@ public:
NPC(LevelGen* mapArg); NPC(LevelGen* mapArg);
~NPC(void); ~NPC(void);
void ForceMove(void);
void Update(void); void Update(void);
void OnPlayerMove(Player* player); void OnPlayerMove(Player* player);
@ -19,15 +20,10 @@ protected:
void Move(void); void Move(void);
private: private:
int _moveChangeFrequency;
int _moveDurationCurrent;
int _moveDurationMin;
int _moveDurationMax;
bool _moving; bool _moving;
Timer _moveTimer; AStarSearch<AStarTile> _astar;
bool _walkInPath;
AStarSearch<MapTile> _astar; AStarTile* _target;
AStarTile* _lastTarget;
}; };

View File

@ -152,7 +152,7 @@ public:
// The user provides this functions and uses AddSuccessor to add each // The user provides this functions and uses AddSuccessor to add each
// successor of node 'n' to _successors. // successor of node 'n' to _successors.
bool ret = n->_userState.GetSuccessors(this, n->parent ? &n->parent->_userState : NULL); bool ret = n->_userState.GetSuccessors(this/*, n->parent ? &n->parent->_userState : NULL*/);
if(!ret) { if(!ret) {
typename vector<Node*>::iterator successor; typename vector<Node*>::iterator successor;

View File

@ -71,6 +71,7 @@ NPC* WorldManager::GetNPCAt(int xArg, int yArg) {
void WorldManager::CreateNPC(int x, int y) { void WorldManager::CreateNPC(int x, int y) {
NPC* npc = new NPC(_level); NPC* npc = new NPC(_level);
npc->SetXY(x, y); npc->SetXY(x, y);
npc->ForceMove();
npc->LoadSprites("../Data/Media/Images/Characters/template.png", 40,45); npc->LoadSprites("../Data/Media/Images/Characters/template.png", 40,45);
_npcs.push_back(npc); _npcs.push_back(npc);
} }

View File

@ -0,0 +1,53 @@
#include "AStarTile.h"
#include "../System/Vec2.h"
#include "../LevelGen/LevelGen.h"
bool AStarTile::IsSameState(AStarTile& tile) {
return tile.x == x && tile.y == y;
}
bool AStarTile::IsGoal(AStarTile& tile) {
return IsSameState(tile);
}
float AStarTile::GoalDistanceEstimate(AStarTile& goal) {
Vec2 goalPos(goal.x * FAKE_SIZE, goal.y * FAKE_SIZE);
Vec2 thisPos(x * FAKE_SIZE, y * FAKE_SIZE);
return fabs(Vec2::DistanceSquared(thisPos, goalPos));
}
float AStarTile::GetCost(AStarTile& goal) {
return FAKE_SIZE * FAKE_SIZE;
}
bool AStarTile::GetSuccessors(AStarSearch<AStarTile>* search) {
if(_level->MetaTilePassable((x - 1) * FAKE_SIZE, y * FAKE_SIZE)) {
AStarTile& successor = _level->GetAStarTile(x - 1, y);
if(!search->AddSuccessor(successor)) {
return false;
}
}
if(_level->MetaTilePassable((x + 1) * FAKE_SIZE, y * FAKE_SIZE)) {
AStarTile& successor = _level->GetAStarTile(x + 1, y);
if(!search->AddSuccessor(successor)) {
return false;
}
}
if(_level->MetaTilePassable(x * FAKE_SIZE, (y - 1) * FAKE_SIZE)) {
AStarTile& successor = _level->GetAStarTile(x, y - 1);
if(!search->AddSuccessor(successor)) {
return false;
}
}
if(_level->MetaTilePassable(x * FAKE_SIZE, (y + 1) * FAKE_SIZE)) {
AStarTile& successor = _level->GetAStarTile(x, y + 1);
if(!search->AddSuccessor(successor)) {
return false;
}
}
return true;
}

View File

@ -0,0 +1,29 @@
#pragma once
#include "../Engine/Pathfinding.h"
class LevelGen;
class AStarTile {
public:
AStarTile() {}
AStarTile(LevelGen* level, int xArg, int yArg, bool passable) : _level(level), x(xArg), y(yArg), _passable(passable) {}
bool IsSameState(AStarTile& tile);
bool IsGoal(AStarTile& tile);
float GoalDistanceEstimate(AStarTile& goal);
float GetCost(AStarTile& goal);
bool GetSuccessors(AStarSearch<AStarTile>* search);
int GetX() { return x * FAKE_SIZE; }
int GetY() { return y * FAKE_SIZE; }
static const int FAKE_SIZE = 64
;
private:
LevelGen* _level;
bool _passable;
int x;
int y;
};

View File

@ -40,6 +40,9 @@ void LevelGen::New(void) {
// procedural generation // procedural generation
DoMagic(); DoMagic();
// pathfinding
UpdateAStarTiles();
} }
void LevelGen::Load(const string& filename) { void LevelGen::Load(const string& filename) {
@ -146,6 +149,8 @@ void LevelGen::Load(const string& filename) {
_world = WorldManager(this); _world = WorldManager(this);
GenerateEnemies(); GenerateEnemies();
UpdateAStarTiles();
} }
void LevelGen::Save(const string& filename){ void LevelGen::Save(const string& filename){
@ -255,7 +260,7 @@ void LevelGen::Unload(void) {
_entityTextures.Unload(); _entityTextures.Unload();
for(int x = 0; x < TILE_ARRAY_SIZE; x++) { for(int x = 0; x < TILE_ARRAY_SIZE; x++) {
for(int y = 0; y < TILE_ARRAY_SIZE; y++) { for(int y = 0; y < TILE_ARRAY_SIZE; y++) {
_tile[x][y] = MapTile(this); _tile[x][y] = MapTile();
} }
} }
} }
@ -448,18 +453,17 @@ void LevelGen::MoveIfPossible(Character* character, float xVel, float yVel, bool
character->SetXY(targetX, targetY); character->SetXY(targetX, targetY);
} }
bool LevelGen::CanMoveToPoint(int xArg, int yArg) { bool LevelGen::MetaTilePassable(int xArg, int yArg) {
if(xArg < 0 || xArg > SCREEN_WIDTH || if(xArg < 0 || xArg > SCREEN_WIDTH ||
yArg < 0 || yArg > SCREEN_HEIGHT) { yArg < 0 || yArg > SCREEN_HEIGHT) {
return false; return false;
} }
/*
int tileX = xArg / TILE_WIDTH; SDL_Rect moverRect;
int tileY = yArg / TILE_HEIGHT; moverRect.x = xArg;
moverRect.y = yArg;
if(_tile[tileX][tileY].GetTileSolidity()) { moverRect.w = 40;
return false; moverRect.h = 45;
}
for(int i = 0; i < BOUNDARIES_X; i++) { for(int i = 0; i < BOUNDARIES_X; i++) {
for(int j = 0; j < BOUNDARIES_Y; j++) { for(int j = 0; j < BOUNDARIES_Y; j++) {
@ -473,16 +477,34 @@ bool LevelGen::CanMoveToPoint(int xArg, int yArg) {
entityRect.w = _tile[i][j].GetEntityWidth(); entityRect.w = _tile[i][j].GetEntityWidth();
entityRect.h = _tile[i][j].GetEntityHeight(); entityRect.h = _tile[i][j].GetEntityHeight();
if(xArg >= entityRect.x && xArg <= (entityRect.x + entityRect.w) && if(CheckCollisionRect(moverRect, entityRect)) {
yArg >= entityRect.y && yArg <= (entityRect.y + entityRect.h)) {
return false; return false;
} }
} }
} }
SDL_Rect playerRect;
playerRect.x = _player->GetX();
playerRect.y = _player->GetY();
playerRect.w = _player->GetWidth();
playerRect.h = _player->GetHeight();
if(CheckCollisionRect(moverRect, playerRect)) {
return false;
}
*/
return true; return true;
} }
void LevelGen::UpdateAStarTiles(void) {
for(int x = 0; x < ASTAR_ARRAY_SIZE; x++) {
for(int y = 0; y < ASTAR_ARRAY_SIZE; y++) {
bool passable = MetaTilePassable(x * AStarTile::FAKE_SIZE, y * AStarTile::FAKE_SIZE);
_astarTile[x][y] = AStarTile(this, x, y, passable);
}
}
}
string LevelGen::GetCurrentMap(void) { string LevelGen::GetCurrentMap(void) {
return _currentMap; return _currentMap;
} }
@ -527,6 +549,6 @@ int LevelGen::GetTileZLevel(int xArg, int yArg) {
return _tile[xArg + 1][yArg + 1].GetZLevel(); return _tile[xArg + 1][yArg + 1].GetZLevel();
} }
MapTile& LevelGen::GetTile(int xArg, int yArg) { AStarTile& LevelGen::GetAStarTile(int xArg, int yArg) {
return _tile[xArg][yArg]; return _astarTile[xArg][yArg];
} }

View File

@ -12,6 +12,7 @@
#include "../Sprite/ImageLoader.h" #include "../Sprite/ImageLoader.h"
#include "../Sprite/ApplySurface.h" #include "../Sprite/ApplySurface.h"
#include "../LevelGen/MapTile.h" #include "../LevelGen/MapTile.h"
#include "../LevelGen/AStarTile.h"
#include "../System/Debug.h" #include "../System/Debug.h"
#include "../Engine/WorldManager.h" #include "../Engine/WorldManager.h"
using namespace std; using namespace std;
@ -32,7 +33,7 @@ public:
void FindSpawnPoint(int& xArg, int& yArg, int objWidth, int objHeight); void FindSpawnPoint(int& xArg, int& yArg, int objWidth, int objHeight);
void MoveIfPossible(Character* character, float xVel, float yVel, bool isPlayer = false); void MoveIfPossible(Character* character, float xVel, float yVel, bool isPlayer = false);
bool CanMoveToPoint(int xArg, int yArg); bool MetaTilePassable(int xArg, int yArg);
bool GetTileSolidity(int xArg, int yArg); bool GetTileSolidity(int xArg, int yArg);
int GetTileX(int xArg, int yArg); int GetTileX(int xArg, int yArg);
@ -46,7 +47,7 @@ public:
int GetTileZLevel(int xArg, int yArg); int GetTileZLevel(int xArg, int yArg);
MapTile& GetTile(int xArg, int yArg); AStarTile& GetAStarTile(int xArg, int yArg);
string GetCurrentMap(void); string GetCurrentMap(void);
@ -60,14 +61,18 @@ private:
void GenerateEntities(const std::string& name, int frequency); void GenerateEntities(const std::string& name, int frequency);
void MakeWalkingPaths(void); void MakeWalkingPaths(void);
void GenerateEnemies(void); void GenerateEnemies(void);
void UpdateAStarTiles(void);
string _currentMap; string _currentMap;
int x; int x;
int y; int y;
static const int TILE_ARRAY_SIZE = 150; static const int TILE_ARRAY_SIZE = 15;
MapTile _tile[TILE_ARRAY_SIZE][TILE_ARRAY_SIZE]; MapTile _tile[TILE_ARRAY_SIZE][TILE_ARRAY_SIZE];
static const int ASTAR_ARRAY_SIZE = TILE_ARRAY_SIZE * (TILE_WIDTH / AStarTile::FAKE_SIZE);
AStarTile _astarTile[ASTAR_ARRAY_SIZE][ASTAR_ARRAY_SIZE];
static const int BOUNDARIES_X = (SCREEN_WIDTH / TILE_WIDTH); static const int BOUNDARIES_X = (SCREEN_WIDTH / TILE_WIDTH);
static const int BOUNDARIES_Y = (SCREEN_HEIGHT / TILE_HEIGHT); static const int BOUNDARIES_Y = (SCREEN_HEIGHT / TILE_HEIGHT);

View File

@ -1,68 +0,0 @@
#include "MapTile.h"
#include "LevelGen.h"
MapTile::MapTile(const MapTile& source) {
_level = source._level;
_tile = source._tile;
_entity = source._entity;
_zLevel = source._zLevel;
}
bool MapTile::IsSameState(MapTile& tile) {
return (tile.GetTileX() == _tile.GetX()) && (tile.GetTileY() == _tile.GetY());
}
bool MapTile::IsGoal(MapTile& tile) {
return IsSameState(tile);
}
float MapTile::GoalDistanceEstimate(MapTile& goal) {
Vec2 thisPos(_tile.GetX(), _tile.GetY());
Vec2 goalPos(goal.GetTileX(), goal.GetTileY());
return abs(Vec2::DistanceSquared(thisPos, goalPos));
}
float MapTile::GetCost(MapTile& goal) {
return 64.0f*64.0f;
}
bool MapTile::GetSuccessors(AStarSearch<MapTile>* search, MapTile* parent) {
int tileX = _tile.GetX() / TILE_WIDTH;
int tileY = _tile.GetY() / TILE_HEIGHT;
// Add tile to the left if possible.
if(tileX > 0) {
MapTile& successor = _level->GetTile(tileX - 1, tileY);
if(successor.GetTileSolidity() || successor.GetEntitySolitity()) {
search->AddSuccessor(successor);
}
}
// Add tile to the right if possible
// TODO: replace 64 with map width
if(tileX < 64) {
MapTile& successor = _level->GetTile(tileX + 1, tileY);
if(successor.GetTileSolidity() || successor.GetEntitySolitity()) {
search->AddSuccessor(successor);
}
}
// Add tile to the bottom if possible
if(tileY > 0) {
MapTile& successor = _level->GetTile(tileX, tileY - 1);
if(successor.GetTileSolidity() || successor.GetEntitySolitity()) {
search->AddSuccessor(successor);
}
}
// Add tile to the top if possible
// TODO: replace 64 with map height
if(tileY < 64) {
MapTile& successor = _level->GetTile(tileX, tileY + 1);
if(successor.GetTileSolidity() || successor.GetEntitySolitity()) {
search->AddSuccessor(successor);
}
}
return true;
}

View File

@ -7,15 +7,11 @@
#include "../Sprite/ApplySurface.h" #include "../Sprite/ApplySurface.h"
#include "../LevelGen/MapElement.h" #include "../LevelGen/MapElement.h"
#include "../LevelGen/MapEntities.h" #include "../LevelGen/MapEntities.h"
#include "../Engine/Pathfinding.h"
#include "../System/Vec2.h"
using namespace std; using namespace std;
class LevelGen;
class MapTile { class MapTile {
public: public:
MapTile(LevelGen* level = NULL) : _level(level) { } MapTile(void) { }
~MapTile(void) { } ~MapTile(void) { }
void Render(void) { _tile.Render(), _entity.Render(); } void Render(void) { _tile.Render(), _entity.Render(); }
@ -33,7 +29,6 @@ public:
int GetTileX(void) { return _tile.GetX(); } int GetTileX(void) { return _tile.GetX(); }
int GetTileY(void) { return _tile.GetY(); } int GetTileY(void) { return _tile.GetY(); }
// Entity Mutators. // Entity Mutators.
void SetEntityTexture(SDL_Surface* arg) { _entity.SetTexture(arg); } void SetEntityTexture(SDL_Surface* arg) { _entity.SetTexture(arg); }
void SetEntityTextureName(string path) { _entity.SetTextureName(path); } void SetEntityTextureName(string path) { _entity.SetTextureName(path); }
@ -52,16 +47,7 @@ public:
void SetZLevel(int arg) { _zLevel = arg; } void SetZLevel(int arg) { _zLevel = arg; }
int GetZLevel(void) { return _zLevel; } int GetZLevel(void) { return _zLevel; }
// Pathfinding stuff.
MapTile(const MapTile& source);
bool IsSameState(MapTile& tile);
bool IsGoal(MapTile& tile);
float GoalDistanceEstimate(MapTile& goal);
float GetCost(MapTile& goal);
bool GetSuccessors(AStarSearch<MapTile>* search, MapTile* parent);
private: private:
LevelGen* _level;
MapElement _tile; MapElement _tile;
MapEntityGeneric _entity; MapEntityGeneric _entity;