Bounce ball off button

In the Paint event of the control you're drawing the ellipse on, you will call DrawEllipse and specify where to draw it. That won't change regardless.

If you want to create animation then you will be using a Timer. In the Tick event handler of the Timer, you will be updating the data that specifies the bounds of your ellipse and then forcing a repaint.

To force a repaint you could just call the Refresh method of the control. That would be the easiest option but not the most efficient, so it would be a mistake. You should look to repaint the smallest area possible so it occurs as quickly as possible and will therefore make your animation smoother. With that in mind, you should invalidate only the areas of the control that have changed, so that only those areas are repainted. To do that, call Invalidate on the control first and specify the current area of the ellipse. You would then modify the data that describes the ellipse and then call Invalidate again and specify the new area. Finally, call Update on the control to raise the Paint event.

Finally, to get the bounce effect. Let's use vertical down/up bounce as an example. Initially, you will be increasing the Y component of the data that defines the ellipse in each Tick event. That means that it will be drawn lower each time and thus appear to move down. You will want to test the lower limit of that area each time to see if it has hit some limit. When it does, you will want to start decreasing the Y component instead, so the ellipse will move up. There's a very simple way to do this. You have a variable that indicates direction, with a value of 1 indicating down and -1 indicating up. Let's say that you want to move the ellipse 5 pixels each time. You simply multiply 5 by the direction variable and add the result, which will be either 5 or -5, to the current Y component of the ellipse area.
 
Back
Top