简体   繁体   中英

Python/Pygame Vector Math

I'm having some trouble with vectors and vector math in a small "battle simulation" program. There are 15 "guys" on each side of the screen, at different X/Y positions. I cannot get the guys to shoot at the correct angle when they choose which enemy they want to shoot at. Currently I have this to determine the bullets path once they shoot. This code is in regards to the bullet rect, and the destination X/Y positions.

    diff = (self.startX - self.destX, self.startY - self.destY)
    distance = math.sqrt(diff[0]**2 + diff[1]**2)
    diff_norm = (diff[0] / distance, diff[1] / distance)
    self.rect.x -= diff_norm[0]
    self.rect.y -= diff_norm[1]

But this just has the bullets all going to the top left(ish) of the screen. the big blue/white squares are the guys, randomly moving about, and the little white squares are the bullets.

http://gyazo.com/8f219a6b0b561b72bcccdea7e325c51a (It's better to view the gif in mp4 format by clicking the "..." in the top right)

Some don't move, some fly straight up...what's happening here?

The problem is that the x and y co-ordinates in a Rect are both integers, and the co-ordinates that you set keep getting rounded down to the nearest integer value each frame.

Because you are normalizing the start->dest vector, it means that all the values in diff_norm are going to be in the range of -1.0 to 1.0, so the rounding that happens is substantial compared to the size of the movements, enough to completely throw it off.

To solve the problem, store values inside your bullets for the current position, initialized when you fire the bullet, that you can manipulate using floating point calculations, then assign the rect x and y based on their value each frame, eg:

self.positionX -= diff_norm[0]
self.positionY -= diff_norm[1]
self.rect.x = int(self.positionX)
self.rect.y = int(self.positionY)

This way the fractional part of the current position isn't getting lost each frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM