Skip to content

Instantly share code, notes, and snippets.

@djaney
Last active October 18, 2018 08:20
Show Gist options
  • Save djaney/e2b22db101ae68a0b89ec48a948946fb to your computer and use it in GitHub Desktop.
Save djaney/e2b22db101ae68a0b89ec48a948946fb to your computer and use it in GitHub Desktop.
Angle to hit a coordinate with a projectile
#!/usr/bin/env python3
import math
import sys
def calculate_angle(velocity, x, y, gravity=9.8, high_angle=False):
angles = []
try:
rad = math.atan( ( velocity**2 + math.sqrt(velocity**4 - gravity * (gravity*x**2 + 2*y*velocity**2) ) ) / (gravity * x) )
angles.append(math.degrees(rad))
except ValueError:
pass
try:
rad = math.atan( ( velocity**2 - math.sqrt(velocity**4 - gravity * (gravity*x**2 + 2*y*velocity**2) ) ) / (gravity * x) )
angles.append(math.degrees(rad))
except ValueError:
pass
if len(angles) == 0:
return None
if high_angle:
return max(angles)
else:
return min(angles)
if __name__ == "__main__":
v = float(sys.argv[1])
x =float(sys.argv[2])
y = float(sys.argv[3])
a = calculate_angle(v, x, y)
if a is None:
a = "Impossible to hit!!!"
print("Angle: {} Velocity: {}m/s Distance: {}m Height: {}m".format(a, v, x, y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment