【问题标题】:Ball stuck at edge of screen [duplicate]球卡在屏幕边缘[重复]
【发布时间】:2021-08-15 19:53:26
【问题描述】:

我制作了一个可以在屏幕上弹跳的球精灵。它适用于底部 和屏幕的右侧,但不是左侧或顶部。 (请注意,x,y 是从 左上角,即左侧的 x 为 0,顶部的 y 为 0)。一旦球触及顶部或左侧,它就会进入并卡在那里。像这样:

这是边缘检测代码:

    def edgedetect(self):

        if self.position.x + self.radius >= width or self.position.x <= self.radius:
            self.velocity.x *= -0.9
            self.velocity.y *= 0.99

        if self.position.y + self.radius >= height or self.position.y <= self.radius:
            self.velocity.y *= -0.9
            self.velocity.x *= 0.99

(x,y分别从左上角算起)

self.position: 保存球心坐标的向量

self.velocity:保存球速度的向量,每帧添加到位置

有没有更好的方法来做到这一点?

【问题讨论】:

  • 问题可能出在代码的其他地方。作为基本调试,尝试打印坐标和速度以查看发生了什么。
  • 在 if 语句中,将位置重置为有效位置。所以如果它越过左边,设置self.position.x = self.radius + 0.1。这样,你就不会因为移动太快而导致球穿过墙壁。我猜这是您的问题,因为您将每帧切换回和第四个速度,因为 if 语句将每帧执行一次。

标签: python pygame


【解决方案1】:

您的边缘检测器应该只切换一次方向,并且在球返回允许区域之前什么都不做:

    def __init__(self, ...):
        ...
        self.is_x_out_of_bounds = False
        self.is_y_out_of_bounds = False

    ...
    
    def edgedetect(self):
        if self.position.x + self.radius >= width or self.position.x < self.radius:
            if not self.is_x_out_of_bounds:
                self.is_x_out_of_bounds = True
                self.velocity.x *= -0.9
                self.velocity.y *= 0.99
        else:
            self.is_x_out_of_bounds = False

        if self.position.y + self.radius >= height or self.position.y < self.radius:
            if not self.is_y_out_of_bounds:
                self.is_y_out_of_bounds = True
                self.velocity.y *= -0.9
                self.velocity.x *= 0.99
        else:
            self.is_y_out_of_bounds = False

除此之外,最好在左边界和上边界碰撞检查中使用 &lt; 而不是 &lt;=,只要 0 是屏幕上点的合法位置。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多