How Can I Bounce the ball everytime it hits the wall???

using GDIDrawer;
using System.Drawing;

            int iX = 0;        //x ball position
            int iY = 0;        //y ball position
            int iXVelocity = 5; //amount ball moves in x direction for every loop
            int iYVelocity = 5; //amount ball moves in y direction for every loop

            //create a drawer window with a scale of 10
            CDrawer Canvas = new CDrawer();
            Canvas.Scale = 5;

            //loop until the ball leaves the visible window
            while ((iX < 160)||(iX > 0))
            {
                //erase the old ball
                Canvas.Clear();

                //draw the new ball
                Canvas.AddEllipse(iX, iY, 1, 1);

                //time delay to slow down the ball
                System.Threading.Thread.Sleep(150);

                //calculate the ball's new position
                iX += iXVelocity;
                iY += iYVelocity;

                //check for bouncing off of the lower edge of the window
                if ((iY > 120)||(iY < 0))
                    //reverse the y velocity (ball goes up)
                    iYVelocity = -iYVelocity;

            }

        }
    }
}

Recommended Answers

All 5 Replies

can't you reset the ball's position everytime?

im not sure i understand your question

I want to know how to make the ball hits a wall, it will bounce and proceed in the opposite direction by 90 degrees?

So far it only bounce just once...after than the ball suddenly gone or erase..

Perhaps a peek at this snippet may set you on the way.

you need reset the ball's coordinates when it touches the borders (line 30), otherwise next time it wont enter the while loop.

The ball steps off the screen and you check its placement and flip the sign. but next time you check its still off the screen so you flip the sign again.

try having a if statement for each wall that also checks the direction of travel before inverting the sign on the velocity.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.