Angle Trigonometry

An example program is at the bottom of the page.



The rectangle on the right rotates to point at the mouse, this is a lot more complex than it may seem.
My finished version is available in source code and exe format at the bottom of the page.

To add a movable shape in small basic use the "shape." function. 
To add the rectangle we use: "Shapes.AddRectangle(width,height)"
To move the rectangle we use: "Shapes.Move(ShapeName,xLocation,yLocation)"
The code to add a simple rectangle use the following:

Add a Rectangle

rectangle = Shapes.AddRectangle(100,10)
Shapes.Move(rectangle,0,250)



Now for the complex part, we need a subroutine to rotate the rectangle when the mouse is moved. To do this we need to use the "GraphicsWindow.MouseMove = rotateRectangle". rotateRectangle is the name of the subroutine that rotated the rectangle.


For the section in the subroutine we need to do some clever maths. What we need to do is work out the angle using tan. tan(angle) = opposite/adjacent
We can draw an imaginary triangle from the mouse to the center of the rectangle. In the diagram Y is the opposite and X is the adjacent. 
tan(angle) = opposite/adjacent
tan(angle) = (mouse Y position - rectangle Y position) / (mouse X position)
angle = tan^-1 ((mouse Y position - rectangle Y position) / (mouse X position))

In small basic syntax:
angle = Math.ArcTan((250-GraphicsWindow.MouseY)/GraphicsWindow.MouseX))

We use GraphicsWindow.Mouse instead of Mouse.Mouse because its X and Y values are relative to the window not the screen. Y increases as we move downwards so we must deduct it from the location of the rectangle centre. 

Another problem is that Math.ArcTan is in radians, so we must convert it to degrees using "Math.GetDegrees".
So angle = Math.GetDegrees(Math.ArcTan((250-GraphicsWindow.MouseY)/GraphicsWindow.MouseX))
250 must be changed to the Y value of the rectangle centre

The final program should look something like this:

Angle Program

GraphicsWindow.MouseMove = rotateRectangle
rectangle = Shapes.AddRectangle(100,10)
Shapes.Move(rectangle,0,250)
Sub rotateRectangle
  angle = Math.GetDegrees(Math.ArcTan((250-GraphicsWindow.MouseY)/GraphicsWindow.MouseX))
  shapes.Rotate(rectangle,-angle)
EndSub
Shapes.Rotate(shapeName,angle in degrees) is used to rotate the shapes, angle must be inverted by using -angle or 0-angle. This will make the rectangle rotate towards the mouse.












ċ
Angle Program.zip
(149k)
Jack Joynson,
4 Mar 2013, 12:41