简体   繁体   English

Python / Pygame矢量数学

[英]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. 屏幕的每一侧有15个“家伙”,位于不同的X / Y位置。 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. 该代码与项目符号和目标X / Y位置有关。

    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) http://gyazo.com/8f219a6b0b561b72bcccdea7e325c51a (最好通过单击右上方的“ ...”以mp4格式查看gif)

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. 问题在于, Rect中的x和y坐标都是整数,并且您设置的坐标会一直向下取整为每帧最接近的整数值。

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. 因为您正在标准化start-> dest向量,这意味着diff_norm中的所有值都将在-1.0到1.0的范围内,因此与移动大小相比,发生的舍入是可观的,足以完全把它扔掉。

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: 要解决该问题,请将子弹内部的值存储在当前位置,并在发射子弹时进行初始化,然后使用浮点计算进行操作,然后根据每帧的值分别指定x和y矩形,例如:

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. 这样,当前位置的小数部分不会在每一帧中丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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