A simple ping pong game in C #

Ping pong

Hi, I am making this game called "Ping Pong". I made an algo for moving the ball. Now I want that when the ball touches or collides with the player (pictured above), it should bounce just like it bounces when it touches the edges. Any suggestions?

For reference. here is a snippet from my code so far ...

private void Ball()
        {
            int x = 1, y = 1, dx = 8, dy = 8;
            System.Drawing.Point p;

            while (true)
            {
                p = player.Location;

                /*
                           here where two or more if statements are required
                */

                if (x < 1)
                    dx = dx + 6;

                if (x >= 800 - ball1.Width)
                    dx = dx - 6;

                if (y < 0)
                    dy = dy + 6;

                if (y > 450 - ball1.Height)
                    dy = dy - 6;

                if (x == -3 && y == -2)
                    dy = dy - 6;

                x = x + dx;
                y = y + dy;

                ball1.Invoke
                (
                    (MethodInvoker) delegate {   ball1.Location = new System.Drawing.Point(x,y);   }
                );

                Thread.Sleep(50);
            } 
+4
source share
1 answer

You do not just need a player’s place, you also need his borders. Then you have several options. The easiest is just to check

if (x - ball1.Width > player.Left && x - ball1.Width < player.Right &&
    y - ball1.Height > player.Top && y - ball1.Height < player.Bottom)

If so, you have a collision and you have to refuse.

, . , , , .

, @drew_w . . - . ( , getBoundingBox , , .)

0

All Articles