Sign in to follow this  
phil67rpg

bounding box colllision

Recommended Posts

I am testing a bounding box collision detection routine. I have been reading up on pointers, functions and classes.However I am still confused about how to pass sprite pointer objects to the SpriteCollision function.

#include <iostream>

using namespace std;

int x,y=10;
int width=64;
int height=64;

class Sprite
{
public:
int x,y;
int width,height;
};

short int Sprite_Collide(Sprite*, Sprite*);

int main()
{
Sprite object1;
Sprite object2;

cout << Sprite_Collide( object1, object2);
return 0;

}

// Object-to-object bounding-box collision detector:
short int Sprite_Collide(Sprite* object1, Sprite* object2)
{
int left1, left2;
int right1, right2;
int top1, top2;
int bottom1, bottom2;

left1 = object1->x;
left2 = object2->x;
right1 = object1->x + object1->width;
right2 = object2->x + object2->width;
top1 = object1->y;
top2 = object2->y;
bottom1 = object1->y + object1->height;
bottom2 = object2->y + object2->height;

if (bottom1 < top2) return(0);
if (top1 > bottom2) return(0);

if (right1 < left2) return(0);
if (left1 > right2) return(0);

return(1);
}


Share this post


Link to post
Share on other sites
If you want to use:

short int Sprite_Collide(Sprite*, Sprite*);

then call Sprite_Collide(&sprite1, &sprite2); // call with pointers


Alternatively, you can define:

short int Sprite_Collide(Sprite&, Sprite&);

and call Sprite_Collide(sprite1, sprite2); // call with references

If you do the latter, then you'll have to change the function to use references:
left1 = object1.x;
left2 = object2.x;
right1 = object1.x + object1.width;
right2 = object2.x + object2.width;

etc.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this