exampleProgram

mail@pastecode.io avatar
unknown
c_cpp
a year ago
2.2 kB
2
Indexable
Never
#include <SFML/Graphics.hpp>
#include <iostream>

#pragma region Player Class
class Player
{
public:
	sf::Vector2f position;
	sf::CircleShape shape;
	sf::RectangleShape bounds;

	//constructor
	Player(sf::Vector2f pos)
	{
		this->position = pos;
		this->shape.setRadius(50.f);
		this->shape.setFillColor(sf::Color(217, 37, 73));
		this->shape.setPosition(position);
		this->bounds.setOutlineThickness(1);
	}

	void update()
	{
		this->shape.setPosition(position);
		this->bounds.setPosition(position);
	}

	void move(sf::Vector2f movementVector)
	{
		this->position += movementVector;
	}

	void draw(sf::RenderWindow& window)
	{
		window.draw(this->shape);
	}

	float GetDistanceBetween(sf::Vector2f pos1, sf::Vector2f pos2)
	{
		return sqrt(pow(pos1.x - pos2.x, 2) + pow(pos1.y - pos2.y, 2));
	}

	void CheckCollision(Player player)
	{
		if (GetDistanceBetween(player.position,this->position) < this->shape.getRadius() + player.shape.getRadius())
		{
			std::cout << "collision" << std::endl;
		}
	}
};
#pragma endregion Player Class


int main()
{	
    sf::RenderWindow window(sf::VideoMode(950, 650), "SFML works!");
	sf:: Event event;
	
	std::vector<Player> players;
	players.push_back(Player(sf::Vector2f(200,200)));
	players.push_back(Player(sf::Vector2f(400,200)));

#pragma region Game Loop
	while (window.isOpen())
	{
		while(window.pollEvent(event))
		{ 
			if (event.type == sf::Event::Closed) 
				window.close();
			
			//if w is pressed, move the first player up
			if (event.type == sf::Event::KeyPressed)
			{
				if (event.key.code == sf::Keyboard::W)
					players[0].move(sf::Vector2f(0, -5));

				if (event.key.code == sf::Keyboard::A)
					players[0].move(sf::Vector2f(-5, 0));

				if (event.key.code == sf::Keyboard::S)
					players[0].move(sf::Vector2f(0, 5));

				if (event.key.code == sf::Keyboard::D)
					players[0].move(sf::Vector2f(5, 0));
			}
		}

#pragma region Drawing	
		window.clear();
	
		for (int i = 0; i < players.size(); i++)
		{
			players[i].update();
			players[i].draw(window);
			players[0].CheckCollision(players[1]);
		}
	
		window.setFramerateLimit(60);
		window.display();
#pragma endregion Drawing
	}
#pragma endregion Game Loop
    return 0;
}