How Do Vectors Work in My Code?

0
21
Asked By CuriousCoder42 On

I'm trying to wrap my head around how Vectors work in programming, specifically in a game development context. I have some code where I'm moving a line by modifying its coordinates, and it works fine with Vectors, but it didn't work with tuples because tuples are immutable. Here's the part of my code:

```python
line1.getLine[0][0] += 2
line1.getLine[1][0] += 2
self.startPos = pygame.math.Vector2(self.x_pos, self.y_pos)
self.endPos = pygame.math.Vector2(self.startPos[0], self.startPos[1] + 70)
```

In contrast, when I used tuples like this:

```python
line1.getLine[0][0] += 2
line1.getLine[1][0] += 2
self.startPos = (self.x_pos, self.y_pos)
self.endPos = ((self.startPos[0]), (self.startPos[1] + 70))
```

it didn't work, likely because I couldn't change the values inside the tuple. I'm also checking out some resources on Desmos to understand the math behind it all. Can someone clarify why Vectors allow me to do this?

2 Answers

Answered By PyDevWizard On

You're right about tuples being immutable; you can’t just change them one value at a time. Vectors in libraries like Pygame tend to be mutable, which allows for quick updates during gameplay. Mutability matters for optimization in games where you need to make frequent updates to positions without the overhead of creating new objects, which is why vectors are often designed this way.

CuriousCoder42 -

That makes a lot of sense! I appreciate the insight into how Vectors are built for speed.

Answered By MathMaven88 On

Vectors can be mutable, allowing you to change their values like you do with `vector[0] = 1` or `vector[1] = 2`. Tuples, on the other hand, are immutable in Python, which means you can't change their values once they're created. When you switched from tuples to Vectors in your code, you gained the ability to directly modify the X and Y coordinates, which is why it worked. This mutable nature of Vectors is particularly useful in game development where performance matters.

CuriousCoder42 -

Thanks for clarifying that! I really like understanding how things work under the hood in my programs.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.