Hello again everybody!
So right now I'm just trying to add some collision. I have a tiled map ( a .txt file with different values for different textures) I'm just going to try for some bounding box collision at the moment. This is what I have so far, but when I move the player into the enemy box, it just gets stuck. How can I fix that, or is there a better way to implement collision with a tiled map? Actually, a better system of implementing collision would be greatly appreciated!
#include <SFML/Graphics.hpp>
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
#include <vector>
const int TILE_SIZE = 32;
class Player
{
public:
sf::RectangleShape rect;
float top, bottom, left, right;
Player(sf::Vector2f position, sf::Vector2f size, sf::Color color)
{
rect.setPosition(position);
rect.setSize(size);
rect.setFillColor(color);
}
void Update(void)
{
top = rect.getPosition().y;
bottom = rect.getPosition().y + rect.getSize().y;
left = rect.getPosition().x;
right = rect.getPosition().x + rect.getSize().x;
}
bool VertCollision(Player p)
{
if (top > p.bottom || bottom < p.top || left > p.right || right < p.left)
return false;
return true;
}
bool HorzCollision(Player p)
{
if (top > p.bottom || bottom < p.top || left > p.right || right < p.left)
return false;
return true;
}
};
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480, 32), "Bounding Box Collision");
Player p1(Player(sf::Vector2f(10, 10), sf::Vector2f(20, 20), sf::Color::Green)),
p2(Player(sf::Vector2f(100, 100), sf::Vector2f(20, 20), sf::Color::Red));
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case::sf::Event::Closed:
window.close();
break;
default:
break;
}
}
p1.Update();
p2.Update();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
p1.rect.move(0, -1.0f);
if (p1.VertCollision(p2))
p1.rect.move(0, 1.0f);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
p1.rect.move(0, 1.0f);
if (p1.VertCollision(p2))
p1.rect.move(0, -1.0f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
p1.rect.move(-1.0f, 0);
if (p1.HorzCollision(p2))
p1.rect.move(1.0f, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
p1.rect.move(1.0f, 0);
if (p1.HorzCollision(p2))
p1.rect.move(-1.0f, 0);
}
window.clear();
window.draw(p1.rect);
window.draw(p2.rect);
window.display();
}
return 0;
}
Thanks!