On my last post (How To Draw 2D Primitive Objects on Windows Forms Application using C++ .NET), we’ve learned about how to draw some 2D objects on Form and Panel. That’s not difficult right? But now, in this post, we’ll learn about how to move that objects. Of course it’ll be very boring if that objects didn’t move. So, let’s get started! Don’t forget that I’m using Microsoft Visual Studio 2008 Professional Edition in this tutorial.
Make a new Visual C++ CLR Windows Forms Application Project. Click File → New → Project…. Choose Visual C++ → CLR → Windows Forms Application and name your Solution Simple2DAnimationUsingTimer.
Then, make a Timer Object inside your Form. Go to the property, change the Interval to 50 (It means that it’ll be active every 50 milliseconds) and change Enabled to true.
Now, let’s go to the code! first, make a Point object that represents the position (Top Left) of the 2D object. In this case, let’s try to make a rectangle. Let’s call it rectanglePos. Then, we make rectangleSpeed to represents the speed of that rectangle when it’s moving.
Next step, let’s initialize this rectanglePos with (0, 0) value and rectangleSpeed with (4, 4) value inside Form1(void) constructor.
Next, let’s make the code inside Form1Paint event to draw the rectangle based on rectanglePos onto your Form window.
Copy the following code inside Form1_Paint().
Now, let’s put some code inside timer1_Tick() to animate (or, actually, it’s only to move) the rectangle. The speed of rectangle move is based on rectangleSpeed. And of course, I’ve put a simple collision detection between rectangle and the wall of Form.
Finally, try to run your program, and it should be like this:
Okay, I think that’s all I got to tell. If you want to make more rectangles or you want to add some circles, just add some Pos and Speed. You can make it by using array or List (try googling if you don’t get it). Okay, hope this simple tutorial gives you some inspirations. See you on my next Post.