Hey, I'm using pyGame and I want to:
A) make a function that returns the angle between two points. I've tried doing this with math.atan2 and I'm getting really wierd returns. I tried this with both (delta X, deltaY) and (deltaY, deltaX). Any suggestions?
B) given a length and an angle, return a point using those two from 0.
For example, LengthDir(2,45) using (length,angle) would return (2,2).
Thanks for the help. I've searched all over the internet and I couldn't find anything to help me...
math.atan2
returns radians. If you need degree, multiply the result by 180/π.
def A(dx, dy):
return math.atan2(dy, dx) * 180 / math.pi
Similarly, all trigonometric functions in math
operate in radians. If you input a degree, you need to multiply by π/180 first.
def LengthDir(length, angle):
radian_angle = angle * math.pi / 180
return (length * math.cos(radian_angle), length * math.sin(radian_angle))
Python provides the convenient functions math.degrees
and math.radians
so you don't need to memorize the constant 180/π.
def A(dx, dy):
return math.degrees( math.atan2(dy, dx) )
def LengthDir(length, angle):
radian_angle = math.radians(angle)
return (length * math.cos(radian_angle), length * math.sin(radian_angle))
You could use the functions in cmath
to convert between rectangular and polar coordinates. For example:
import math, cmath
def LengthDir(r, phi):
c = cmath.rect(r, math.radians(phi))
return (c.real, c.imag)
def AngleBetween((x1, y1), (x2, y2)):
phi = cmath.phase(x2 + y2*j) - cmath.phase(x1 + y1*j)
return math.degrees(phi) % 360
import math
def dist(dx,dy):
return math.sqrt(dx*dx + dy*dy)
def ang(dx, dy):
return math.degrees(math.atan2(dy, dx))
def offs(dist, ang):
ang = math.radians(ang)
dx = dist * math.cos(ang)
dy = dist * math.sin(ang)
return dx,dy
.
dist(2,2) -> 2.8284
ang(2,2) -> 45.0
offs(2, 45) -> (1.414, 1.414)