How to Make an Object Bounce in C#

How to Make an Object Bounce in C# thumbnail
Make a ball bounce in C#.

Making an object bounce in a Microsoft Visual C# application can be accomplished easily by using a few form properties and a timer control. C# is a programming language included in the Microsoft Visual Studio suite, and it can be used to create Windows Forms applications. Bouncing objects are often used in game applications, such as a ball bouncing inside a form. Use a timer control to keep track of the size of the form and reposition the ball accordingly.

Things You'll Need

  • Microsoft Visual Studio installed
Show More

Instructions

    • 1

      Launch Microsoft Visual Studio. Click “New Project” on the left pane of the application window and expand “Other Languages” below “Installed Templates.” Click “Visual C#” and double-click “Windows Forms Application” from the center of the dialogue window to create a new project.

    • 2

      Double-click the form to create a new Form Load event. Insert the following code above “public Form1()” to create four integer global variables in this module:

      int dx;
      int dy;
      int x;
      int y;

    • 3

      Copy and paste the following code inside the “Form1_Load” event to generate a random number:

      Random rnd = new Random();
      dx = rnd.Next(1, 4);
      dy = rnd.Next(1, 4);
      x = rnd.Next(0, this.ClientSize.Width - 50 );
      y = rnd.Next(0, this.ClientSize.Height - 50);

    • 4

      Switch back to form design and right-click the form. Click “Properties” and click the "Events" icon, which resembles a lighting strike. Double-click next to “Paint” to create the event. Copy and paste the following code inside the event:

      e.Graphics.Clear(this.BackColor);
      e.Graphics.FillEllipse(Brushes.Black, x, y, 50, 50);
      e.Graphics.DrawEllipse(Pens.Black, x, y, 50, 50);

    • 5

      Switch back to form design and double-click “Timer” to add a new one to your project. Right-click the timer control and click “Properties.” Set “Enabled” to “True” and set “Interval” to “1.” Double-click the timer control to create a tick event. Add the following code to reposition the object:

      x += dx;
      if (x < 0)
      {
      dx = -dx;
      }
      else if (x + 50 > this.ClientSize.Width)
      {
      dx = -dx;
      }

      y += dy;
      if (y < 0)
      {
      dy = -dy;
      }
      else if (y + 50 > this.ClientSize.Height)
      {
      dy = -dy;
      }
      this.Invalidate();

    • 6

      Press “F5” to run the program and watch the ball bounce back and forth. Resize your form to bounce the ball faster or slower.

Related Searches:

References

  • Photo Credit Comstock Images/Comstock/Getty Images

Comments

Related Ads

Featured