Hello,
I'm using SFML to make a game, and, as it has no built-in collision detection function, I made up my own algorithm. Here it is:
// Collision.cpp
#include "Collision.h"
Side CollisionBoxTest(sf::Sprite Hitter, sf::Sprite Hittee)
{
sf::Rect<int> HitterBox;
sf::Rect<int> HitteeBox;
// Initialize parameters for Hitterbox
int BoxHeight = Hitter.GetHeight();
int BoxWidth = Hitter.GetWidth();
sf::Vector2f BoxPos = Hitter.GetPosition();
// Pass parameters to HitterBox
HitterBox.Left = BoxPos.x;
HitterBox.Right = BoxPos.x + BoxWidth;
HitterBox.Top = BoxPos.y;
HitterBox.Bottom = BoxPos.y + BoxHeight;
// Change the parameters to HitteeBox
BoxHeight = Hittee.GetHeight();
BoxWidth = Hittee.GetWidth();
BoxPos = Hittee.GetPosition();
// Pass parameters to HitteeBox
HitteeBox.Left = BoxPos.x;
HitteeBox.Right = BoxPos.x + BoxWidth;
HitteeBox.Top = BoxPos.y;
HitteeBox.Bottom = BoxPos.y + BoxHeight;
// Test for collision by examining the two rects created around the sprite's images
if(HitterBox.Bottom >= HitteeBox.Top && HitterBox.Top <= HitteeBox.Bottom &&
HitterBox.Right >= HitteeBox.Left && HitteeBox.Left <= HitteeBox.Right)
return LEFT;
else
return NULL;
}
// Collision.h
#ifndef COLLISION_H
#define COLLISION_H
#include <SFML/Graphics.hpp>
enum Side { LEFT, RIGHT, TOP, DOWN, NULL };
Side CollisionBoxTest(sf::Sprite ObjectA, sf::Sprite ObjectB);
#endif
CollisionBoxTest()
returns LEFT if the sprites in question are colliding. Of course, I don't always want it to return LEFT. I want it to return the side that the hitter hit, but I don't have any idea of how I would go about this. Does anyone have a suggestion/idea?