问题描述
我能够成功地在我的 Pygame 游戏中实现加速,但是有一点问题.问题是:角色减速后,角色会开始向一个方向加速,减速并开始向另一个方向加速,减速并开始向相反方向加速,无休止地重复这两件事.我怎样才能让它停止?
I was able to successfully implement acceleration into my Pygame game, but there is a bit of a problem.Problem is: After the character decelerates, the character will start accelerating in one direction, decelerate and start accelerating in another direction, decelerate and start accelerating in opposite direction, repeating those two things endlessly. How would i get this to stop?
这是我为加速编写的代码:
Heres the code i wrote for acceleration:
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
推荐答案
加速度只取决于输入,如果没有输入,加速度为零:
The acceleration depends on the input only, if there is no input, the acceleration is zero:
accel = 0
if move_R:
accel += PLAYER_ACCEL
if move_L:
accel -= PLAYER_ACCEL
速度因加速度而变化,但因摩擦力而减小.
The velocity changes by the acceleration, but it is reduced by the friction.
veloc = (veloc + accel) * (1 - PLAYER_FRICT)
注意,在某一点上,加速度不能补偿摩擦力.全部加速能量被摩擦消耗.
如果veloc/(veloc + accel)
等于1 - PLAYER_FRICT
,则运动是均匀的.
Note, at a certain point, the acceleration can not compensate the friction. The complete acceleration energy is consumed by the friction.
If veloc / (veloc + accel)
is equal 1 - PLAYER_FRICT
, the movement is uniform.
玩家的位置随当前速度变化:
The position of the player changes by the current velocity:
player_xy[0] += veloc
最小示例:
Minimal example:
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()
这篇关于减速Pygame后如何修复角色在两个方向上不断加速?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!