# Collision with corners of a picturebox – C#

Printable View

• December 9th, 2012, 07:04 AM
Thomas1207
Collision with corners of a picturebox – C#
Hi,

I’m having a problem with collision between 2 pictureboxes.

The situation: I have a picturebox that represents a ball and that bounces around the form. In the middle of the form I’ve got another picturebox which is fixed. When the ball hits either the top or the bottom of the picturebox, it must be ricocheted / thrown back in the opposite Y-direction.

When the ball hits either the left or the right side of the picturebox, it must be thrown back in the opposite X-direction.

I already have the code for the situation above and it works! But I’ve got a problem when the ball hits one of the four corners of the picturebox. Does anyone know how I could fix this??

Code:

```private void gameAreaCollisions() {     if (picBoxBal.Bounds.IntersectsWith(picBoxMidden.Bounds))     {         if (picBoxBal.Top < picBoxMidden.Top && picBoxMidden.Top <= picBoxBal.Bottom)               BalSpeedY = -BalSpeedY;         else if (picBoxBal.Top <= picBoxMidden.Bottom && picBoxMidden.Bottom < picBoxBal.Bottom)               BalSpeedY = -BalSpeedY;         else // collision with left or right side               BalSpeedX = -BalSpeedX;     } }```
thanks in advance !
• December 9th, 2012, 04:37 PM
BioPhysEngr
Re: Collision with corners of a picturebox – C#
Is the problem that when it hits the corners, it only inverts the speed in the Y direction, instead of in both directions? If so, this is a consequence of using the if-else if-else structure (since either the Y speed will change OR the X speed will change, never both). You can fix it by using four ifs (actually, if you combine the first two and last two statements, you can do it in two ifs, but I thought this was more explanatory):

Code:

```if( the top was hit )     reverse y if( the bottom was hit)     reverse y if( the left was hit )     reverse x if( the right was hit)   reverse x```
If that isn't the problem, you'll have to explain what you want and what is happening.

Hope that helps!
• December 10th, 2012, 08:59 AM
Thomas1207
Re: Collision with corners of a picturebox – C#
Hi,

I first had something in mind like your piece of code but it didn't work.
Either the ball went through the picturebox or I had an error because I couldn't use "IntersectsWith".

Maybe you have a better idea how to work out that piece of pseudo-code of yours??

The problem I've got with my code when the ball hits the corners: the ball goes through the picturebox
from left to right or vice versa. This happens either at the top side or at the bottom. It looks like a sort of 'lag'
but it isn't.

Thanks for your answer btw
• December 12th, 2012, 10:48 AM
Thomas1207
Re: Collision with corners of a picturebox – C#
Is there perhaps someone who has a better idea for code then mine to solve this problem?

Thanks!