Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What do the pygame.math.Vector2 parameters indicate?

I’m trying to figure out how to create a unit vector / normalized Vector2 instance given an angle (degrees). I encountered the following as I was reading pygame’s documentation at https://www.pygame.org/docs/ref/math.html#pygame.math.Vector2 :

Vector2() -> Vector2
Vector2(int) -> Vector2
Vector2(float) -> Vector2
Vector2(Vector2) -> Vector2
Vector2(x, y) -> Vector2
Vector2((x, y)) -> Vector2

To my understanding, they generate the following vectors:

Vector2() -> (0, 0)
Vector2(Vector2) -> (Vector2.x, Vector2.y)
Vector2(x, y) -> (x, y)
Vector2((x, y)) -> (x, y)

But what do int and float parameter datatypes indicate? Also, please correct if I have misunderstood the above assumptions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Moreover, can I instantiate a normalized Vector2 object given an angle or do I need to do some trigonometry with math library first?

>Solution :

I’m trying to figure out how to create a unit vector / normalized Vector2 instance given an angle

The length of a unit vector is 1, so the simplest way to create a unit vector with a given angle is:

v = pygame.math.Vector2(1, 0)
v.rotate_ip(angle)

Alternatively, you can create the vector with the trigonomentry functions sin and cos:

angle_radian = math.radians(angle_degree)
v = pygame.math.Vector2(math.cos(angle_radian), math.sin(angle_radian))

All vector constructors construct a vector with the specified scalars. The constructors with only one argument create a vector where the x and y components are equal.

You can easily find out yourself by using print:

print(pygame.math.Vector2())
print(pygame.math.Vector2(1))
print(pygame.math.Vector2(1.5))
print(pygame.math.Vector2(2, 3))
print(pygame.math.Vector2((2.5, 3.5)))

Output:

[0, 0]
[1, 1]
[1.5, 1.5]
[2, 3]
[2.5, 3.5]

int and float indicates that you can construct the vector with integral and floating point numbers, however this has no effect on the behavior of the object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading