pygame 如何以恒定速度向鼠标发射子弹?

How do you shoot bullet towards mouse in pygame at a constant speed?

我正试图向 pygame 中的鼠标发射子弹,这是我的代码:

import pygame
import math

pygame.init()

screen = pygame.display.set_mode((400, 400))

pygame.display.set_caption("diep.io")

screen.fill((255,255,255))

auto_shoot = False

class Bullet:
  def __init__(self, x_move, y_move, x_loc, y_loc):
    self.image = pygame.image.load("Bullet.png")
    self.x_move = x_move
    self.y_move = y_move
    self.x_loc = x_loc
    self.y_loc = y_loc
    self.bullet_rect = self.image.get_rect()
  
  def update(self):
    self.bullet_rect.center = (self.x_loc + self.x_move, self.y_loc + self.y_move)
    self.x_loc = self.bullet_rect.center[0]
    self.y_loc = self.bullet_rect.center[1]
    screen.blit(self.image, self.bullet_rect)

    if self.x_loc > 400 or self.y_loc > 400:
      bullets.remove(self)

bullet = None
bullets = []

while True:
  screen.fill((255, 255, 255))
  pygame.draw.rect(screen, (100, 100, 100), (205, 193, 25, 15))
  pygame.draw.circle(screen, (82, 219, 255), (200, 200), 15)
  for event in pygame.event.get():
    if event.type == pygame.MOUSEBUTTONUP:
      x = pygame.mouse.get_pos()[0] - 200
      y = pygame.mouse.get_pos()[1] - 200
      pythag = float(math.sqrt(x**2 + y**2))
      bullets.append(Bullet(x/pythag, y/pythag, 200, 200))
  for bullet in bullets:
    bullet.update()
  pygame.display.update()
  pygame.time.delay(10)

我对如何使这项工作感到困惑,我想我以某种方式四舍五入,但即使在我放入 float() 之后,它仍然无法工作。另外,在我使用鼠标坐标之前,它是有效的,但是当靠近坦克时,它射击很慢,而离坦克越远则速度快得离谱。有没有人帮忙,谢谢!

由于pygame.Rect应该表示屏幕上的一个区域,因此pygame.Rect对象只能存储整数数据。

The coordinates for Rect objects are all integers. [...]

当对象的新位置分配给 Rect 对象时,坐标的小数部分丢失。
你必须反过来做。更改 self.x_locself.y_loc,但更新 self.bullet_rect.center:

class Bullet:
  # [...]

  def update(self):
    self.x_loc += self.x_move
    self.y_loc += self.y_move   
    self.bullet_rect.center = round(self.x_loc), round(self.y_loc)

    rect = screen.blit(self.image, self.bullet_rect)
    if not screen.get_rect().contains(rect):
      bullets.remove(self)

另请参阅以下问题: and .