I'm attempting to rewrite the classic snake game in c++
. What I am inquiring about is my implementation for a 2D collision detection function. I am utilizing SFML
to create the window and shapes. The two objects that I am checking are squares of the same size. I would really appreciate any feedback that is given, as I'm still a beginner when it comes to c++
.
This function works as intended. I'm looking for performance improvements, and general c++
practices that I should follow. If I need to add any more code, please let me know.
Game.h
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
class Game {
// Some code omitted for brevity //
private:
sf::RectangleShape enemy;
sf::RectangleShape player;
public:
const bool isColliding(sf::RectangleShape player, sf::RectangleShape enemy) const;
// Some code omitted for brevity //
};
Game.cpp
/*
Determines if the player is colliding with the enemy.
@param sf::RectangleShape player - Player object.
@param sf::RectangleShape enemy - Enemy object.
@return bool - True if colliding, False otherwise.
*/
const bool Game::isColliding(sf::RectangleShape player, sf::RectangleShape enemy) const {
sf::Vector2f playerPosition = this->player.getPosition();
sf::Vector2f enemyPosition = this->enemy.getPosition();
float playerWidth = this->player.getSize().x;
float playerHeight = this->player.getSize().y;
return (
((playerPosition.x + playerWidth) > enemyPosition.x && (playerPosition.x - playerWidth) < enemyPosition.x) &&
((playerPosition.y + playerHeight) > enemyPosition.y && (playerPosition.y - playerHeight) < enemyPosition.y)
);
}