Border Collision Detection - Bouncing Control

To make a label (or any other control.. I just choose label as an example) bounce when it hits the border of a form you'll have to invert the speed with which the label is incremented each tick.

Here's an example:

I will use a label which I've called lblAI, two speed int (AISpeedX and AISpeedY - the speeds with which the label moves on the X and Y axis), two const int (SCREEN_WIDTH and SCREEN_HEIGHT) and one timer which I've called gameTime. Also I've added one Panel called gameArea, but it's not really required.

First we will have to declare our variables just above the constructor:

        const int SCREEN_WIDTH = 700;
        const int SCREEN_HEIGHT = 400;
        int AISpeedX = 3;
        int AISpeedY = 2;

Then we will need to give an initial location to the label. We can do this in the Form1_Load event:

private void Form1_Load(object sender, EventArgs e)
        {
            lblAI.Location = new Point(SCREEN_WIDTH / 2 - lblAI.Width / 2, SCREEN_HEIGHT / 2 - lblAI.Height / 2);
        }

The next step would be to add the Tick event to our timer and inside it we will move the label by incrementing the speed values. Also, at each tick we will check to see if the label's location does not exit the form's borders. For this example I've used a 1 millisecond interval for a smooth result, but you can user whatever you like. Also, remember to enable the timer as it is disabled by default.

private void gameTime_Tick(object sender, EventArgs e)
        {
            if (lblAI.Location.X < 0 || lblAI.Location.X > (SCREEN_WIDTH - lblAI.Width)) AISpeedX = -AISpeedX;
            if (lblAI.Location.Y < 0 || lblAI.Location.Y > (SCREEN_HEIGHT - lblAI.Height)) AISpeedY = -AISpeedY;

            lblAI.Location = new Point(lblAI.Location.X + AISpeedX, lblAI.Location.Y + AISpeedY);
        }

As you can see, at each tick we check to see if the Location on the X axis is lower than 0 or higher than the screen width, and if it is we invert the incrementation value on the X axis. Same goes for the Y axis.

You can notice that when checking for the higher value I've subtracted the label's width for the X axis and the label's height for the Y axis. I did this because we are using the label's location value which is given by the top left point of the label. If we wouldn't have had subtracted the width and the hight respectively we would see the label leave the area until the location point would have been greater than the width or height of the area.

No comments:

Post a Comment