VB icon

Calculate Angles from the coords of three points

Email
Submitted on: 1/6/2015 5:16:00 PM
By: Kevin Laity (from psc cd)  
Level: Intermediate
User Rating: By 3 Users
Compatibility: VB 4.0 (16-bit), VB 4.0 (32-bit), VB 5.0, VB 6.0
Views: 1346
 
     This code is useful in games where you need to calculate an angle quickly. Using three points it gives you the angle, in degrees, of the vertex.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
				
'**************************************
' Name: Calculate Angles from the coords of three points
' Description:This code is useful in games where you need to calculate an angle quickly. Using three points it gives you the angle, in degrees, of the vertex.
' By: Kevin Laity (from psc cd)
'
' Inputs:Three sets of coordinates: A center point, and the ends of two lines coming from the center.
'
' Returns:The angle of the vertex in degrees
'**************************************

Function LineLen(x1, y1, x2, y2)
	'This function will simply give you the length
	'of a line using the coordinates of its two
	'endpoints.
	Dim A, B As Single
	A = Abs(x2 - x1)
	B = Abs(y2 - y1)
	LineLen = Sqr(A ^ 2 + B ^ 2)
End Function
Function Arccos(X As Single)
	If X = 1 Then Arccos = 0: Exit Function
	Arccos = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)
End Function
Public Function CalcAnAngle(CenterX, CenterY, x2, y2, x3, y3)
	'This function will take three coordinates and
	'automagically turn them into an angle.
	'The angle is the one located at CenterX, CenterY
	'For example:
	'/ X2,Y2
	'/
	' /
	' < CenterX,CenterY
	' 	'	'\ X3,Y3
	'CalcAnAngle will return the angle, in degrees,
	'of the center vertex.
	On Error Resume Next
	Dim SideA, SideB, SideC As Single
	SideC = lineLen(CenterX, CenterY, x2, y2)
	SideB = lineLen(CenterX, CenterY, x3, y3)
	SideA = lineLen(x3, y3, x2, y2)
	a = Arccos((SideA ^ 2 - SideB ^ 2 - SideC ^ 2) / (SideB * SideC * -2))
	CalcAnAngle = a * (180 / 3.141)
	'VB seems to like to work in confusing units
	'called Radians instead of good ol' degrees.
	'Multiplying by (180 / 3.141) converts radians
	'to degrees.
End Function


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.