How can I do AABB collision engine? What do I need? I need it to do a platformer game (don't want to use box2d etc.).
I tried to make it like this
void GameplayScreen::Update()
{
ePlayer->Update();
collision();
}
void GameplayScreen::Draw(SDL_Renderer *renderer)
{
DrawMap(renderer);
ePlayer->Draw(renderer);;
}
void GameplayScreen::DrawMap(SDL_Renderer *renderer)
{
for (int y = 0; y < map.size(); ++y)
for (int x = 0; x < map[y].size(); ++x)
if (map[y][x] != 0)
{
SDL_Rect destRect;
SDL_Rect srcRect;
srcRect.w = 32;
srcRect.h = 32;
srcRect.x = blockID * srcRect.w;
srcRect.y = 0;
destRect.x = (x * 32);
destRect.y = (y * 32 ); /
destRect.w = 32;
destRect.h = 32;
vBlock[Earth]->Draw(renderer, srcRect, destRect);
}
}
void GameplayScreen::Collision()
{
for(int y = 0; y < map.size(); ++y)
for(int x = 0; x < map[y].size(); ++X)
if(map[y][x] != 0)
{
int mapX = x * 32;
int mapY = y * 32;
int mapW = x * 32 + 32; // I tried (x + 32) * 32 also
int mapH = y * 32 + 32; // I tried (y + 32) * 32 also
int playerX = ePlayer->getPosX();
int playerY = ePlayer->getPosY();
int playerW = ePlayer->getPosX() + ePlayer->getHitBoxX();
int playerH = ePlayer->getPosY() + ePlayer->getHitBoxY();
AABB aabb(mapX, mapY, mapW, mapH);
if(aabb.chechCollision(playerX, playerY, playerW, playerH))
{
//I don't know what do write here
//I wrote what I thought would be good
if(playerX <= mapW && playerX >= mapX)
{
std::cout<<"Player collision Left"<<std::endl;
}
else if(playerW >= mapX && playerW <= mapW)
{
std::cout<<"Player collision right"<<std::endl;
}
else if(playerY <= mapH && playerH >= mapH)
{
std::cout<<"Player collision top" <<std::endl;
}
else if(playerH >= mapY && playerH <= mapH)
{
std::cout<<"player collision bot"<<std::endl;
}
}
else std::cout<<"NO COLLISION"<<std::endl;
}
}
bool AABB::checkCollision(float x1, float y1, float w1, float h1)
{
if ((x <= w1 && x >= x1)
&& (w >= x1 && w <= w1)
&& ((y <= h1 && h >= h1)
|| h >= y1 && h <= h1)) // I tried here with &&
{
return true;
}
return false;
}
The problem with this is that, even if map[y][x] == 0 => no collision.
The game says that there is a collision.