Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the angle between 2 points in pygame?

I am writing a game in Python with Pygame.
The co-ords (of my display window) are
( 0 , 0 ) at the top left and
(640,480) at the bottom right.

The angle is
when pointing up,
90° when pointing to the right.

I have a player sprite with a centre position and I want the turret on a gun to point towards the player. How do I do it?
Say,
x1,y1 are the turret co-ords
x2,y2 are the player co-ords
a is the angle's measure

like image 261
Matt Randell Avatar asked May 06 '12 20:05

Matt Randell


People also ask

How do you find angles in Pygame?

Normally, you'd use atan2(dy,dx) but because Pygame flips the y-axis relative to Cartesian coordinates (as you know), you'll need to make dy negative and then avoid negative angles. ("dy" just means "the change in y".) degs ought to be what you're looking for.

How do you find the angle between two points in Python?

The tangent of the angle between two points is defined as delta y / delta x That is (y2 - y1)/(x2-x1). This means that math. atan2(dy, dx) give the angle between the two points assuming that you know the base axis that defines the co-ordinates.

How do you find the angle between two vectors in Pygame?

We can calculate the angle between two vectors by the formula, which states that the angle of two vectors cosθ is equal to the dot product of two vectors divided by the dot product of the mod of two vectors. A, B are two vectors and θ is the angle between two vectors A and B.


2 Answers

First, math has a handy atan2(denominator, numerator) function. Normally, you'd use atan2(dy,dx) but because Pygame flips the y-axis relative to Cartesian coordinates (as you know), you'll need to make dy negative and then avoid negative angles. ("dy" just means "the change in y".)

from math import atan2, degrees, pi
dx = x2 - x1
dy = y2 - y1
rads = atan2(-dy,dx)
rads %= 2*pi
degs = degrees(rads)

degs ought to be what you're looking for.

like image 110
mgold Avatar answered Sep 18 '22 12:09

mgold


Considering a triangle

sin(angle)=opposed side / hypotenuse
like image 39
ChristopheCVB Avatar answered Sep 21 '22 12:09

ChristopheCVB