Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Collision checking problem?  (Read 1559 times)

0 Members and 1 Guest are viewing this topic.

gaz99

  • Newbie
  • *
  • Posts: 7
    • View Profile
Collision checking problem?
« on: February 27, 2012, 02:03:13 am »
Hi i recently had problems with using rects but figured out what i was doing wrong now i'm still having problems detecting more than one collision at the same time. the following code allows collision with the red blocks and does react to the blue blocks but does not destroy them?

Code: [Select]

for(int x=0; x <60 ; ++x)
{
if((ballR.Intersects(rBLOCK.getRect(x))))
{
if (!(rBLOCK.getCollide(x))) //if not collided
{
_angle =  360.0f - (_angle - 180.0f);
if(_angle > 360.0f){ _angle -= 360.0f;}
moveByY = -moveByY;
rBLOCK.setCollide(x, true);
++ destroyedBlocks;

}
}

else if((ballR.Intersects(bBLOCK.getRect(x))))
{
if((!(bBLOCK.getCollide(x))))
{
_angle =  360.0f - (_angle - 180.0f);
if(_angle > 360.0f){ _angle -= 360.0f;}

moveByY = -moveByY;
bBLOCK.setCollide(x, true);
++ destroyedBlocks;
}
}
}



but if i change the else if to an if it  does destroy both blocks like it should however the ball does not bounce back like it should but instead keeps going until it collides with the top or edge of the screen.

Could anyone help me out ?
sorry if i haven't explained it properly.

texus

  • Hero Member
  • *****
  • Posts: 505
    • View Profile
    • TGUI
    • Email
Collision checking problem?
« Reply #1 on: February 27, 2012, 03:57:27 pm »
Quote
if i change the else if to an if it does destroy both blocks like it should
This is normal, if you keep "else if" then you will not check for collision on the blue block when you already found a colliding red block.

Quote
moveByY = -moveByY;

This is were your problem lies.
You check if the ball collides with the red block and you change the direction of the ball.
Then (if not using 'else if') you will change it again when colliding with the blue block. This is why it keeps going.

My advice would be the following: (I didn't think about this long, so there might be a better solution)
- Use 'if' and not 'else if', because you need to check collision with both blocks.
- Use a bool CollisionDetected, which is set to false in the beginning of the function. If the ball collides with the red block then you make it true. When the ball collides with the blue block then you don't invert the direction of the ball when CollisionDetected was already true.
TGUI: C++ SFML GUI

gaz99

  • Newbie
  • *
  • Posts: 7
    • View Profile
Collision checking problem?
« Reply #2 on: February 27, 2012, 06:24:49 pm »
ahhh thank you i did what you said and got it working didn't realise that was happening. Thank you again!

 

anything