Home Articles My Account Messages Tools Join
Tech Blog, ASP.Net, VB.Net, C#.Net, Programming Help, Help Guide
StellarPC.com | Useful Trig Functions For Game Programming (VB.Net)
Useful Trig Functions For Game Programming (VB.Net)
Written by: Justin Rich

Useful Trig Functions For Game Programming

Trigonometry is very useful when programming games. This has to do with the fact that most of the time you're calculating angles in degrees or radians, and distance between 2 points on the screen. Below I've given you a few good functions to calculate the angle of 2 points and their distance. This will help in making several kinds of game tools.


Public Class Trig
Public Shared Function CalculatePointAngle(ByVal pointStart As Point, ByVal pointEnd As Point) As Double
Dim dy As Double = -(pointEnd.Y - pointStart.Y)
Dim dx As Double = (pointEnd.X - pointStart.X)

Dim angleRadians As Double = Math.Atan2(dy, dx)

If (angleRadians < 0) Then
angleRadians += 2 * Math.PI
End If

Dim angleDegrees As Double = RadiansToDegrees(angleRadians)

Return angleDegrees
End Function

Public Shared Function CalculatePointDistance(ByVal pointStart As Point, ByVal pointEnd As Point) As Double
Dim dySquared As Double = Math.Pow(pointEnd.Y - pointStart.Y, 2)
Dim dxSquared As Double = Math.Pow(pointEnd.X - pointStart.X, 2)

Dim distance = Math.Sqrt(dySquared + dxSquared)

Return distance
End Function

Public Shared Function RadiansToDegrees(ByVal angle As Double) As Double
Return ((angle * 180) / Math.PI)
End Function

Public Shared Function DegreesToRadians(ByVal angle As Double) As Double
Return ((angle * Math.PI) / 180.0F)
End Function

End Class


The code above will enable you to calculate the distance between two (2) points, calculate the angle between two (2) points, convert radians to degrees, and convert degrees to radians.

I used this class to drag and drop a line in my game that represents the angle and velocity to which I want to throw something, grabbing the points of the line, calculating their distance for velocity and their angle for the launch angle. Then, I used it to manage the angle of my projectile as it glided through the air. The game was written in Silverlight and should be available soon on http://www.StellarGamer.com

Stellar Gamer will be a Silverlight Game Portal for all people to post their games to. As of 2/18/2009 the site is available, but still beta.
New Post Next 50 | Previous 50
Post# Subject: Posted By: Time:
New Post Next 50| Previous 50