If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Hybrid View

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??

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!

Best Regards,

BioPhysEngrhttp://blog.biophysengr.net
--
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Re: Collision with corners of a picturebox  C#

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.