首页 > 解决方案 > 如何在pygame中为我的角色添加加速?

问题描述

我对 python 和 pygame 有点陌生,我需要一些与加速有关的帮助。我在 youtube 上遵循了一个关于如何为平台游戏制作基础的教程,并且我一直在使用它来创建一个玩起来像 Kirby 游戏的游戏。我在 Kirby 游戏中注意到的一个小细节是,当你朝一个方向移动然后快速转向另一个方向时,他是如何打滑的,在过去的几天里,我一直在研究如何让它发挥作用。我想出的解决方案是让角色不再只是在按下一个键时移动,而是角色将加速,然后在达到最大速度后停止加速,然后在你按下另一个键时快速减速并再次加速方向键。问题是,我不知道如何编程加速。谁能帮我这个?

这是我为游戏编写的代码(第一位用于碰撞,第二位用于实际移动玩家):

def move(rect, movement, tiles):
collide_types = {'top': False, 'bottom': False, 'right': False, 'left': False}
rect.x += movement[0]
hit_list = collide_test(rect, tiles)
for tile in hit_list:
    if movement[0] > 0:
        rect.right = tile.left
        collide_types['right'] = True
    if movement[0] < 0:
        rect.left = tile.right
        collide_types['left'] = True
rect.y += movement[1]
hit_list = collide_test(rect, tiles)
for tile in hit_list:
    if movement[1] > 0:
        rect.bottom = tile.top
        collide_types['bottom'] = True
    if movement[1] < 0:
        rect.top = tile.bottom
        collide_types['top'] = True

return rect, collide_types

第二位:

player_move = [0, 0]
if move_right:
    player_move[0] += 2.5
elif run:
    player_move[0] += -3
if move_left:
    player_move[0] -= 2
elif run:
    player_move[0] -= -3
player_move[1] += verticle_momentum
verticle_momentum += 0.4
if verticle_momentum > 12:
    verticle_momentum = 12
elif slow_fall == True:
    verticle_momentum = 1

if fly:
    verticle_momentum = -2
    slow_fall = True
    if verticle_momentum != 0:
        if ground_snd_timer == 0:
            ground_snd_timer = 20

标签: pythonpygame

解决方案


您应该更改速度,而不是直接更改按钮按下时角色的位置。例如,仅在 X 轴上移动:

acc = 0.02 # the rate of change for velocity
if move_right:
    xVel += acc 
if move_left:
    xVel -= acc 

# And now change your character position based on the current velocity
character.pose.x += xVel 

您可以添加的其他内容:做到这一点,当您不按任何键时,您会失去动力,因此您可以停下来。您可以通过从速度中减去或添加某个衰减因子来做到这一点(该衰减因子小于您的加速度常数,但您必须在试验游戏时对其进行调整)。


推荐阅读