We need a graphics program which will draw a square around a given circle and allow the user to rotate the square to any angle he/she chooses. That's it.
This program came about because I was having a terrible time elevating the cannon in the cannonball program. After going back to basics and writing this program, the cannon elevation problem was a snap.
The overall plan of the program is to calculate the position of the four corners of the square each time the user changes the angle. An OnChange exit from the trackbar calls a MakeBox procedure to recalculate the 4 corners for the new angle. MakeBox ends with an Invalidate call to tell windows that it needs to redraw something whenever it gets a chance.
An OnPaint event exit is used to actually draw the 4 lines that make up the sides of the square. We must do it in an OnPaint exit, otherwise the square would disappear whenever the screen was redrawn.
Two functions, Rotate and Translate, do the rotation of points. Rotation about an origin point of (0,0) is straightforward as you'll see from the code. Once we have the point rotated to the desired angle relative to then origin, Translate can move the point by adding the new x and y origin coordinates to the x and y values of the point.
The trig required to derive the rotation equations is straightforward if you assume that the original angle of the point from the origin is A and we want to rotate by B degrees, then the new angle from the origin is A+B. Then, remembering good old Indian chief "Soh Cah Toa" (Sin=Opposite/Hypotenuse, etc.), and looking up the identities for sin(A+B) and cos(A+B), the rest is easy.
| Move the Polyline function call from the OnPaint exit to the MakeSquare function and see how it works. | |
| Remove the Invalidate call at the end of Makebox - does it still work OK? | |
| Remove the DoubleBuffered=true from FormActivate to see flicker as Windows erases the square before redrawing it. | |
| You could try rotating other shapes - triangles, hexagons, etc. Circles don't work very well. | |
| But by placing different sized circles at appropriate distances and with some information about lengths of solar years, you could make a nice animated model of the solar system. That's such a neat idea, I think I'll add it my list of programs to write. |