python - 敌人射弹攻击快速问题的方法
问题描述
我试图让我的敌人子弹攻击玩家,但它的攻击方式快速我不知道为什么VIDEO 我的敌人子弹类
# enemys bullets
ksud = pygame.image.load("heart.png")
class Boolss(object):
def __init__(self, x, y,color, xspeed, yspeed):
self.x = x
self.y = y
self.xspeed = xspeed
self.yspeed = yspeed
self.ksud = pygame.image.load("heart.png")
self.hitbox = self.ksud.get_rect()
self.rect = self.ksud.get_rect()
self.rect.topleft = (self.x,self.y)
self.color = color
self.hitbox = (self.x + 57, self.y + 33, 29, 52) # NEW
def draw(self, window):
self.rect.topleft = (self.x,self.y)
player_rect = self.ksud.get_rect(center = self.rect.center)
player_rect.centerx += 0 # 10 is just an example
player_rect.centery += 0 # 15 is just an example
window.blit(self.ksud, player_rect)
self.hitbox = (self.x + 97, self.y + 33, 10, 10) # NEW
window.blit(self.ksud,self.rect)
这是它附加子弹的地方,就像攻击玩家一样
for shootss in shootsright:
shootss.x += shootss.xspeed
shootss.y += shootss.yspeed
if shootss.x > 500 or shootss.x < 0 or shootss.y > 500 or shootss.y < 0:
shootsright.pop(shootsright.index(shootss))
if len(shootsright) < 1:
start_x = round(enemyshoots1.x+enemyshoots1.width-107)
start_y = round(enemyshoots1.y + enemyshoots1.height-50)
target_x = playerman.x+playerman.width//2
target_y = playerman.y+playerman.width//2
dir_x, dir_y = target_x - start_x, target_y - start_y
distance = math.sqrt(dir_x**2 + dir_y**2)
if distance > 0:
shootsright.append(Boolss(start_x,start_y,(0,0,0),dir_x, dir_y))
#------------------------------------------------------------------------------
解决方案
问题在这里:
start_x = round(enemyshoots1.x+enemyshoots1.width-107)
start_y = round(enemyshoots1.y + enemyshoots1.height-50)
target_x = playerman.x+playerman.width//2
target_y = playerman.y+playerman.width//2
dir_x, dir_y = target_x - start_x, target_y - start_y
如果您打印dir_x
并且dir_y
您会看到这些值非常高。您可能会将此值添加到每一帧到项目符号的位置。这就是为什么它们在你真正看到它们之前就离开了屏幕。
你可以试试这个:
BULLET_SPEED = 5
delta_x, delta_y = target_x - start_x, target_y - start_y
distance = math.sqrt(delta_x ** 2 + delta_y ** 2)
dir_x = BULLET_SPEED * delta_x / distance
dir_y = BULLET_SPEED * delta_y / distance
考虑到这个解决方案不会对值进行四舍五入,并且 pygame 可能会因为与浮点值的坐标而引发异常。在使用它们进行绘图之前,您应该对坐标进行四舍五入。
推荐阅读
- python - 将图像合并到 z-stack 中并在 Python 中进行最大投影 /
- javascript - 如何将数据导入到 gatbsy-config.js
- python - 如何修复所需的位置参数?
- php - 在 WP Shortcode 中显示来自 mySQL 的数据字段
- r - 'Sum' 函数返回 TRUE 或 FALSE 值而不是数字?
- spring - 更新现有 elasticsearch 实例的集群名称
- ios - UIApplicationDelegate 如何强制其“window”为“internal”而不是“private”,但是当名称更改为“door”时可以吗?
- python - 从另一个数组更新 numpy 2d 数组索引
- reactjs - 如何在 useEffect 挂钩中形成 setFieldValue
- python - 将列一一添加到新的 DataFrame