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?

Best way to figure these types of problems out is by using some paper.

Draw each case you want on paper (in this situation you want to see four ways another box can hit the "hittee") then write out the conditions that have to be met.

Also what happens if you move diagonally into the box?

also just want to point out a spelling mistake that could give you a headache: "&& HitteeBox.Left <= HitteeBox.Right)"

This article has been dead for over six months. Start a new discussion instead.