I am going to try to start releasing useful code snippets each week. While I can’t guarrantee I can release a snippet every week, I will try to write some interesting snippet and release it as often as I can. The code snippets will range from game play to tool development. So with that aside, lets begin!

Recently I have been working on a pool game. I needed to be able to rotate the stick about the cue ball. At first glance, to the untrained mathematician, this may seem like a complex task. However it isn’t that bad… really!

Take a look at the following image,

As you can see, when dealing with rotations, the cosine determines where your point should be on the X axis while the sine determines where your point should be on the Y axis. When you plug in a value into both the cosine and sine functions, you will get a point that is located on the circle’s edge or rather a rotation about the origin. If our cue ball is centered at the origin, and our stick is the diagnol line extruding from the origin, all we need to do is increase/decrease the angle of the stick in order to rotate it around the cue ball or origin. The following code shows how to do that in ActionScript 3.0.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // We will want to rotate the stick based // on the mouse's position. So add an event listener // for the mouse move event. stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouse); function handleMouse(evt:MouseEvent): void { // Get the difference between the coordinates of // the mouse and cue ball. var dx:Number = evt.stageX - ball1.x; var dy:Number = evt.stageY - ball1.y; // Given the difference in xy coordinate positions, // the atan2 trig function will return the angle between // our stick and cue ball. var fAlpha:Number = Math.atan2(dy, dx); // Physically move the stick based on the Alpha angle // Starting from the cue ball's origin, rotate about the // cue ball by angle "fAlpha" and then move 50 pixels // away. stick.x = ball1.x + (Math.cos(fAlpha) * 50); stick.y = ball1.y + (Math.sin(fAlpha) * 50); // Convert the angle from radians to degrees // and change the stick's rotational value. stick.rotation = (180 * fAlpha) / Math.PI; } |

Well that is it for now. Stay tuned for more useful snippets. If you have any particular requests, please feel free to email them to me.