gpt4 book ai didi

python - 如何修复Pygame减速后角色不断向两个方向加速的问题?

转载 作者:行者123 更新时间:2023-12-01 00:07:48 25 4
gpt4 key购买 nike

我能够成功地在我的 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

最佳答案

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

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()

关于python - 如何修复Pygame减速后角色不断向两个方向加速的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59832445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com