Search code examples
pythonvector

How to initiate and unpack vectors in python?


So I am using pygame to learn python and I got the following problem:

I am trying to create a gravity vector (angle, length), like so:

gravity = pygame.math.Vector2(math.pi, 0.01)

I've also tried:

gravity = (math.pi, 0.01)

But when I try to use the gravity variable in my code I get errors saying that I didn't pass enough parameters, as if it treated the gravity variable as a single value.

When I break it down, for example by doing this:

... , gravity[0], gravity[1], ...

It works just fine.

Here's an example function that I want to use with the vector (it takes 4 float values as parameters):

(self.angle, self.speed) = add_vectors(self.angle, self.speed, gravity[0], gravity[1])

(This one works)

(self.angle, self.speed) = add_vectors(self.angle, self.speed, gravity)

(this one doesn't work)

What is causing this? Am I initiating the vector wrong or would I have to keep unpacking it by using gravity[0] for example?


Solution

  • Your gravity variable is a tuple, which is only one object. Your method expects to have 4 arguments but you are passing 3 in the latter example. You could use argument unpacking / destructing.

    add_vectors(self.angle, self.speed, *gravity)
    

    See more about unpacking here: https://www.geeksforgeeks.org/packing-and-unpacking-arguments-in-python/