【问题标题】:How to fix character constantly accelerating in both directions after deceleration Pygame?减速Pygame后如何修复角色在两个方向上不断加速?
【发布时间】:2020-01-20 23:57:39
【问题描述】:

我能够成功地在我的 Pygame 游戏中实现加速,但是有一点问题。 问题是:角色减速后,角色会开始向一个方向加速,减速并开始向另一个方向加速,减速并开始向相反方向加速,无休止地重复这两件事。我怎样才能让它停止?

这是我为加速编写的代码:

if move_R == True:
    accel = PLAYER_ACCEL
if move_L == True:
    accel = -PLAYER_ACCEL

accel += veloc * PLAYER_FRICT
veloc += accel
player_xy[0] += veloc + 0.5 * accel

【问题讨论】:

  • 嗯,从某种意义上说,这似乎是一个无限循环,加速度随着速度不断增加 * 摩擦和速度随着加速度不断增加,也许你可以提供如何获得 PLAYER_FRICT
  • 你能实现速度的最大限制吗? veloc = min( veloc, MAX_VELOCTY )
  • PLAYER_FRICT 在我的代码中存储 -0.12 以上。很抱歉我忘记包含它。
  • 为什么 == Trueif ... == True: 中?你认为那有什么作用?我们可能需要更多您的程序。请参阅:minimal reproducible example

标签: python pygame


【解决方案1】:

加速度只取决于输入,如果没有输入,加速度为零:

accel = 0
if move_R:
    accel += PLAYER_ACCEL
if move_L:
    accel -= PLAYER_ACCEL

速度因加速度而变化,但因摩擦而减小。

veloc = (veloc + accel) * (1 - PLAYER_FRICT)

注意,在某一点,加速度不能补偿摩擦。全部的加速能量都被摩擦所消耗。
如果veloc / (veloc + accel) 等于1 - PLAYER_FRICT,则运动是均匀的。

玩家的位置随当前速度变化:

player_xy[0] += veloc

小例子:

import pygame

pygame.init()

size = 500, 500
window = pygame.display.set_mode(size)
clock = pygame.time.Clock()

border = pygame.Rect(0, 0, size[0]-40, 100)
border.center = [size[0] // 2, size[1] // 2]
player_xy = [size[0] // 2, size[1] // 2]
radius = 10
PLAYER_ACCEL, PLAYER_FRICT = 0.5, 0.02
veloc = 0

run = True
while run:
    clock.tick(120)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # set acceleration in this frame
    accel = 0
    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT]:
        accel += PLAYER_ACCEL
    if keys[pygame.K_LEFT]:
        accel -= PLAYER_ACCEL
    
    # change velocity by acceleration and reduce dependent on friction
    veloc = (veloc + accel) * (1 - PLAYER_FRICT)

    # change position of player by velocity
    player_xy[0] += veloc

    if player_xy[0] < border.left + radius:
        player_xy[0] = border.left + radius
        veloc = 0
    if player_xy[0] > border.right - radius:
        player_xy[0] = border.right - radius
        veloc = 0

    window.fill(0) 
    pygame.draw.rect(window, (255, 0, 0), border, 1)
    pygame.draw.circle(window, (0, 255, 0), (round(player_xy[0]), round(player_xy[1])), radius)
    pygame.display.flip()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多