Problems with loading collision detection code into function

Coders forum. Discuss techniques, swap code snippets, ask for help etc. relating to all forms of software development.
Post Reply
SadisticToaster
Baa!
Baa!
Posts: 39
Joined: Sat Jun 11, 2005 8:05 pm 0

Problems with loading collision detection code into function

Post by SadisticToaster »

Hey.

I've only just started out in SDL , and have run into a problem. The collision detection code below works perfectly when it's in the main function. however , I didn't like having the code repeated for each collsion check , and so copied it into a function.

Here something goes wrong. :(

Have spent the last few days swearing at the complier , but have not managed to figure it out. Basically , rather then destroying the object which the bullet hits ( in this case house bricks' , as it's a space invaiders clone ) , the bullet will destroy every object in it's Y axis path ( alothough the bullet is still removed from the game when it hits the first brick , every other single object in it;s path also dies )

Here is the code :

if (imageoverlap(fire.x,fire.y,120+(12*xx),165+(12*(yy-1)),bullet->w,brick->w,bullet->h,brick->h))
{
fire.active=0;
house2[xx] =0;
}

int imageoverlap(int ob1x,int ob1y,int ob2x,int ob2y,int ob1w,int ob2w,int ob1h,int ob2h)

{
if ((ob1x >ob2x) && (ob1x < ob2x + ob2w))
{
if ((ob1y > ob2y)&& ((ob1y < ob2y) + ob2h))
{
return 1;
}
}

if ((ob1x+ob1w >ob2x) && (ob1x+ob1w < ob2x + ob2w))
{
if ((ob1y > ob2y)&& ((ob1y < ob2y) + ob2h))
{
return 1;
}
}
return 0;
}

Many thanks for any help
"Have you ever tried a pink golf ball, Wally? Why, the wind shear alone on a pink golf ball will take the head clean off a 90 pound midget at 300 yards"
User avatar
[Feeblez]
Baaaa!
Baaaa!
Posts: 961
Joined: Mon Dec 02, 2002 2:03 pm 0
Location: neither here nor there, UK

Post by [Feeblez] »

This is how i would do it, notice the parameter order has changed...

Code: Select all

int imageoverlap( int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2 )
{
	if( ((x1 + w1) > x2) && ((y1 + h1) > y2) && (x1 < (x2 + w2)) && (y1 < (y2 + h2)) )
	{
		return 1;
	}
	return 0;  
}
EDIT: I think i see your problem, your brackets are screwed up...

Code: Select all

int imageoverlap(int ob1x,int ob1y,int ob2x,int ob2y,int ob1w,int ob2w,int ob1h,int ob2h) 

{ 
if ((ob1x >ob2x) && (ob1x < ob2x + ob2w)) 
{ 
if ((ob1y > ob2y)&& ((ob1y < ob2y) + ob2h)) <--- Oops!
if ((ob1y > ob2y)&& (ob1y < (ob2y + ob2h))) <--- Better?
{ 
return 1; 
} 
} 

if ((ob1x+ob1w >ob2x) && (ob1x+ob1w < ob2x + ob2w)) 
{ 
if ((ob1y > ob2y)&& ((ob1y < ob2y) + ob2h)) <--- Oops!
if ((ob1y > ob2y)&& (ob1y < (ob2y + ob2h))) <--- Better?
{ 
return 1; 
} 
} 
return 0; 
}
Post Reply