【问题标题】:How to shoot a bullet at an angle in pygame?如何在pygame中以一定角度射击子弹?
【发布时间】:2018-09-06 22:56:36
【问题描述】:

我在 pygame 中制作游戏,当你发射子弹时,子弹的运动方向与你的鼠标移动的方向相同。这是我的Player 课程代码:

class Player(pygame.sprite.Sprite):
    def __init__(self, game, x, y):
        self.game = game
        pygame.sprite.Sprite.__init__(self, game.all_sprites)
        self.image = pygame.Surface((50, 50))
        self.image.fill(settings.player_color)

        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = x, y
        self.pos = Vector2(x, y)

        self.speed = Vector2(0, 0)

        self.is_shooting = False

    def update(self):
        self.pos += self.speed
        self.rect.x, self.rect.y = self.pos.x, self.pos.y

    def shoot(self):
        self.is_shooting = True
        m_x, m_y = pygame.mouse.get_pos()
        b_m_x, b_m_y = m_x - self.pos.x, m_y - self.pos.y
        b = Bullet(self.game, self.rect.x - 50, self.rect.y - 50 / 2, b_m_x, b_m_y)
        _, angle = (pygame.mouse.get_pos() - self.pos).as_polar()
        b.rotate(_)

我制作子弹路径的方式是让子弹有一个像线一样的斜率。 b_m_xb_m_yx 的变化和y 的变化。

我今年才刚开始学习代数(我 13 岁),去年我学会了如何绘制线性线,所以如果有更简单的方法来制作子弹路径,请告诉我。

这是我的子弹类代码

class Bullet(pygame.sprite.Sprite):
    def __init__(self, game, x, y, run, rise):
        pygame.sprite.Sprite.__init__(self, game.all_sprites)
        self.image = pygame.Surface((15, 50))
        self.image.fill((255, 0, 0))

        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = x, y
        self.pos = pygame.math.Vector2(self.rect.x, self.rect.y)
        self.speed = pygame.math.Vector2(x=run / settings.bullet_speed_offset, y=rise / settings.bullet_speed_offset)

    def update(self):
        self.pos += self.speed
        self.rect.x, self.rect.y = self.pos.x, self.pos.y

    def rotate(self, angle):
        self.image = pygame.transform.rotozoom(self.image, angle, 1)
        self.rect = self.image.get_rect()

我的问题是我的鼠标离Player sprite越远,子弹飞得越快(因为当我找到线的斜率时,鼠标和玩家之间的差异越大,速度越快子弹的速度将是)。如何制作更好的子弹发射系统?

【问题讨论】:

    标签: python math pygame bulletphysics bullet


    【解决方案1】:

    如果你希望速度不依赖于鼠标距离,你应该标准化到鼠标的距离。

    换句话说,无论鼠标在哪里,都使用同一方向上的点的坐标,但与起始位置有固定距离,例如当你计算你的b_m_xb_m_y时,这样做:

    b_m_x, b_m_y = m_x - self.pos.x, m_y - self.pos.y
    
    distance = (b_m_x ** 2 + b_m_y ** 2) ** .5
    
    if distance != 0:
        # if distance is 0, nothing can be done
    
        NORMALIZED_DISTANCE = 100
        mutiplier = NORMALIZED_DISTANCE / distance
    
        b_m_x *= multipler
        b_m_y *= multipler
    

    【讨论】:

    • 这有效,但我的问题仍然出现的唯一时间是鼠标在播放器下方时
    • 没关系,我通过设置 distance = (b_m_x ** 2 + b_m_y ** 2) ** .5 而不是 distance = (b_m_x ** 2 + b_m_x ** 2) ** 来修复它。 5.我将第二个 b_m_x 更改为 b_m_y
    • @Shaan 是的,那是我的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多