如何在pygame中为我的角色添加加速度?

3
我是新手,对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
1个回答

3

在按下按钮时,不应直接改变角色的位置,而应该改变速度。例如,仅在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 

你可以添加其他的控制方式:当你不按键时,减少速度或添加衰减系数(要比加速度小),这样使得角色逐渐停下来。


它没有起作用。如果这有帮助的话,我没有将玩家存储在自己的类中,因此我没有任何对应于玩家位置的东西。 - 24_cleo
啊,但是代码不会像那样工作,我只是给你一个关于如何实现你所要求的内容的整体想法。你需要在自己的代码中实现类似的东西。如果你不存储位置,你怎么显示你的字符呢? - mdgr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接