Sprite collision method

Hello, I am rather new to c++ (I've done Java previously) and I'm working on trying to make a collision method. This is what I have so far:
1
2
3
4
5
6
7
8
9
10
11
bool Collision(bool collision){

	//collision code *I think it should work...*
	if((tankX >= turretX && tankX <= (turretX + turretW)) || ((tankX + tankW) >= turretX && (tankX + tankW) <= (turretX + turretW))){
		if((tankY >= turretY && tankY <= (turretY + turretH)) || ((tankY + tankH) >= turretY && (tankY + tankH) <= (turretY + turretH))){

			return true;
		}
	}
	return true;
}


At the moment though from what I can tell, this doesn't work... So in my main function I have this code to test for a collision:
1
2
3
4
5
Collision(collision);//calls collision function to check collisions

	if(collision == true){
		m_Screen->Print("COLLISION", 2, 2, 0xffffff);//prints collision in top left corner
	}


I can't it to detect collisions, at least not print the line...
Anyone know what I'm doing wrong? Any help is much appreciated.
Last edited on
I can't get it to run.


A compilation error? What's the error?
Ah I miss-worded that ehm, the program runs but the Collision() function doesn't detect collisions :/
Can you see anything wrong with the function I wrote?
Your function always return true.
Your code is hard to follow. I think that you want return between( turret, tank, turrent+size );

Also collision == true == true == true == true == true == true == true == true == true //...
I believe you want something more along the lines of:
1
2
3
4
5
6
7
8
9
10
11
bool Collision(){

	//collision code *I think it should work...*
	if((tankX >= turretX && tankX <= (turretX + turretW)) || ((tankX + tankW) >= turretX && (tankX + tankW) <= (turretX + turretW))){
		if((tankY >= turretY && tankY <= (turretY + turretH)) || ((tankY + tankH) >= turretY && (tankY + tankH) <= (turretY + turretH))){

			return true;
		}
	}
	return false;
}
1
2
3
4
if(Collision())//calls collision function to check collisions
{
   m_Screen->Print("COLLISION", 2, 2, 0xffffff);//prints collision in top left corner
}
Chaining together a million && and || conditions is ugly. Look at how confusing that is. As a general rule, if you're doing more than one &&/|| in a single conditional, you're probably making it too complicated (there are exceptions to that rule, of course).

I say Simplify it!

1
2
3
4
5
6
7
8
9
10
bool Collision()
{
  if(tankX    > (turrentX + turrentW))  return false;  // tank to the right of the turrent
  if(turrentX > (   tankX +    tankW))  return false;  // tank to the left of the turrent
  if(tankY    > (turrentY + turrentH))  return false;  // tank below
  if(turrentY > (   tankY +    tankH))  return false;  // tank above

  // if none of those were true, then the tank must be on top of the turret
  return true;
}
Topic archived. No new replies allowed.