I want to implement a "knockback" in my 2D game, but I have no idea how to do it. I've found some tutorials on google but nothing help. (My knowledge about math is a little limited when we're talking about Cartesian plane)
Well let's just figure out, I have the player and the monster on my map (2 vectors) and when I touch the monster, BOOOM, I get "knockbacked" at the OPPOSITE direction (not left, right, top or bottom) that I touch him.
I have the following code on my project:
CollisionManager.cpp
CollisionManager::CollisionManager()
{
}
CollisionManager::~CollisionManager()
{
}
bool CollisionManager::checkCollisionWithWall(SDL_Rect box, std::vector<Tile*> tiles)
{
return touchesWall(box, tiles);
}
void CollisionManager::checkCollisionEnemy(Player * player, GameObject * enemy)
{
if (enemy->type() == std::string("Enemy"))
{
return;
}
if (SDL_HasIntersection(&player->getCollisionBox(), &enemy->getCollisionBox()))
{
player->collision(enemy);
}
}
The player's collision function (almost nothing here):
void Player::collision(GameObject* collisionObject)
{
isKnockbacking = true;
hp -= 2;
}
Ahh and my moving function is inherited from my Entity class:
void Entity::checkTileCollision(std::vector<Tile*> tiles)
{
if (isKnockbacking == false) {
//Move the dot left or right
v2DPosition.m_x += v2DVelocity.m_x;
collisionBox.x = v2DPosition.m_x;
//If the dot collided or went too far to the left or right
if ((v2DPosition.m_x < 0) ||
(v2DPosition.m_x + 18 > Game::Instance()->getScreenWidth()) ||
collisionManager->checkCollisionWithWall(collisionBox, tiles))
{
//Move back
v2DPosition.m_x -= v2DVelocity.m_x;
collisionBox.x = v2DPosition.m_x;
}
//Move the dot up or down
v2DPosition.m_y += v2DVelocity.m_y;
collisionBox.y = v2DPosition.m_y;
//If the dot collided or went too far up or down
if ((v2DPosition.m_y < 0) ||
(v2DPosition.m_y + 18 > Game::Instance()->getScreenHeight()) ||
collisionManager->checkCollisionWithWall(collisionBox, tiles))
{
//Move back
v2DPosition.m_y -= v2DVelocity.m_y;
collisionBox.y = v2DPosition.m_y;
}
}
}
I've followed LazyFoo, SDL Game Development book and some other tutorials on YouTube to make it.
If I need to be more specific, just tell me.