954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Change collision detection algorithm to return which side is hit

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?

Chuckleluck
Junior Poster in Training
54 posts since Sep 2011
Reputation Points: 10
Solved Threads: 1
 

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?

sfuo
Practically a Master Poster
656 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99
 

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

Eagletalon
Junior Poster
113 posts since Mar 2011
Reputation Points: 47
Solved Threads: 13
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: