pygame - pygame中的摩擦

标签 pygame

<分区>

对于我的平台游戏,我想让它在移动时慢慢减速。我尝试了几种方法,但没有用,它只是停留在原地。有人可以帮助我吗?

class Player(pygame.sprite.Sprite):

    def __init__(self, game):
        pygame.sprite.Sprite.__init__(self)
        self.game = game
        self.speedx = 0
        self.speedy = 0
        self.alive = True

        self.image = pygame.Surface((30, 40))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.bottom = HEIGHT - 10
        self.rect.centerx = WIDTH / 2

    def update(self):
        self.speedx = 0
        self.speedy = 0
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_a]:
            self.speedx = -10
        elif key_pressed[pygame.K_d]:
            self.speedx = 10
        if key_pressed[pygame.K_SPACE]:
            self.speedy = -10

        self.speedx += self.rect.x
        self.speedx *= FRICTION
        self.speedy += self.rect.y

        if self.rect.left < 0:
            self.rect.x = 0
        elif self.rect.right > WIDTH:
            self.rect.right = WIDTH

最佳答案

就我个人而言,我更喜欢这样计算摩擦力:

  • 如果按下某个键,我会在速度上加上每秒 3000 像素
  • 每一帧,我都会通过将速度乘以一个非常接近 1 的数字来减慢 Sprite 的速度,例如当游戏以每秒 100 帧的速度运行时为 0.95。

通过使用这种技术,如果您让 Sprite 移动,它会加速得越来越快。如果你停止移动它,它会平稳地减速。此外,如果您让 Sprite 在它仍在向右移动时向左移动,它会更快地“转身”。

你可以乱用这些值:如果你增加第一个数字,速度就会增加。如果第二个数字更接近 1,则摩擦力不那么显着。


以下是在以每秒 100 帧的速度运行时如何编写代码:

x_speed 变量以像素/秒为单位。只需将其除以 100 即可得到每帧像素。

# in the game loop

pressed = pygame.key.get_pressed()
if pressed[K_RIGHT]:
    x_speed += 30
if pressed[K_LEFT]:
    x_speed -= 30

x_speed *= 0.95

这里是如何使用它,为了以任何帧速率运行游戏(你只需要一个变量,time_passed,它对应于花在帧上的时间,以秒为单位:你可以使用 pygame.time.Clock()

x_speed 变量以像素/秒为单位。

# in the game loop

pressed = pygame.key.get_pressed()
if pressed[K_RIGHT]:
    x_speed += 3000 * time_passed
if pressed[K_LEFT]:
    x_speed -= 3000 * time_passed

x_speed *= 0.95**(100 * time_passed)

Runnable Minimal, Reproducible Example:

关于pygame - pygame中的摩擦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68158829/

相关文章:

python - 在pygame中按多次键来移动图像

python - 缩放 Sprite 大小

python - 如何在pygame中不让文本相互重叠?

python-3.x - 在 pygame 中渲染抗锯齿透明文本

python - Pygame 和线程

python-3.x - 按下按钮即可持续移动

python - 如何在Python 3.7中使用Pygame显示用Pillow加载的图像?

Python只运行一次while循环

python - 在屏幕上显示 PyGame Mask

python - “int”对象不可调用?