BLOG.CSHARPHELPER.COM: Draw an animation of a piston driving a wheel in C#
Draw an animation of a piston driving a wheel in C#
This example draws a piston that powers a rotating wheel. The program uses a timer to move the piston. The following code shows the timer's event handler.
// Move the piston. private void tmrMovePiston_Tick( object sender, EventArgs e) { X += Dx;
if ((X < Xmin) || (X > Xmax)) { Dx = -Dx; X += 2 * Dx; }
DrawSystem(); picCanvas.Refresh(); }
The event handler simply adds Dx to the X position of the piston. If X goes beyond its allowed bounds, the event handler reverses the sign of Dx to make the piston move in the other direction next time.
The timer's event handler then calls the following DrawSystem method to draw the picture.
Most of this code is simply drawing. The only real trick is figuring out how the wheel should be rotated. The trick is find the end points of the green rod that connects the piston to the wheel.
The first end point is at the end of the piston.
The trick to finding the second end point is to notice that it must lie on the wheel and it must lie on the dashed circle centered at the end of the piston as shown in the picture on the right. Mathematically that end point lies at the intersection of the dashed circle and the circle defined by the wheel.
The example Determine where two circles intersect in C# explains how to determine where two circles intersect. This example uses the FindCircleCircleIntersections method described by that example.
Note that two circles may intersect in two places, as they do in this example. That means there are two possible configurations for this system. In the second configuration, the second end point is at the bottom of the wheel. When the piston is pulling back, the DrawSystem method uses that solution so the rod's second end point moves all the way around the circle instead of just moving back and forth over the top of the wheel.
The picture on the right shows the complete program. Use the textboxes to experiment with the length of the connecting rod and the wheel's radius.
Comments