Skip to main content
 首页 » 编程设计

python之以奇怪的角度发射的子弹pygame

2025年05月04日12kerrycode

我在 pygame 中编写一个 2d 自上而下的射击游戏,我遇到了一个问题,我试图发射的子弹的矢量图形。子弹在发射,但它们并没有像它们应该的那样朝光标发射。我以前遇到过这种情况,我知道它与我在下面提供的子弹移动功能代码有关,但我不知道我做错了什么。

要查看他们发射的奇怪角度,请在此处运行完整文件 https://github.com/hailfire006/economy_game/blob/master/shooter_game.py

class Bullet: 
    def __init__(self,mouse,player): 
        self.x = player.x 
        self.y = player.y 
        self.name = "bullet" 
        self.speed = 13 
        self.mouse = mouse 
        self.dx,self.dy = self.mouse 
    def move(self): 
        distance = [self.dx - self.x, self.dy - self.y] 
        norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2) 
        direction = [distance[0] / norm, distance[1] / norm] 
        bullet_vector = [direction[0] * self.speed, direction[1] * self.speed] 
 
        self.x -= bullet_vector[0] 
        self.y -= bullet_vector[1] 
 
    def draw(self): 
        square = pygame.Rect((self.x,self.y),(20,20)) 
        pygame.draw.rect(screen,(200,100,40),square) 

编辑:修正了拼写错误

请您参考如下方法:

您的代码有 3 个问题。 @DTing 已经提到了错字。这使得子弹朝着相反的方向前进。

要让子弹与鼠标点击的方向相同,您需要更改以下行:

self.x -= bullet_vector[0] 
self.y -= bullet_vector[1] 

到

self.x += bullet_vector[0] 
self.y += bullet_vector[1] 

现在你的子弹正朝着正确的方向前进,但一旦到达你点击鼠标的位置,它们就会停止。这是因为您每次移动都会获得子弹矢量。您可以在 init 函数中获取它一次,它们只是在每次后续调用中重复使用它。以下是我为使代码正常工作所做的更改:

def __init__(self,mouse,player): 
    self.x = player.x 
    self.y = player.y 
    self.name = "bullet" 
    self.speed = 13 
    self.mouse = mouse 
    self.dx,self.dy = self.mouse 
    distance = [self.dx - self.x, self.dy - self.y] 
    norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2) 
    direction = [distance[0] / norm, distance[1] / norm] 
    self.bullet_vector = [direction[0] * self.speed, direction[1] * self.speed] 
 
def move(self): 
    self.x += self.bullet_vector[0] 
    self.y += self.bullet_vector[1] 

您的代码现在将按预期工作。