Pygame, Character Movement Speed

放肆的年华 提交于 2019-12-20 07:35:54

问题


I am a student at the University of Utah and am working on a project in Pygame that I am having minor trouble with. I have coded the entirety of the game, and it runs perfectly, but I would like my character to slow movement when walking over certain terrain. For example, if he/she walks over a sand tile than I would like for his/her speed to cut in half. I have not been able to figure this out on my own as I am still learning. The link to my code is below. Any help would be much appreciated!

I believe the solution will come within these lines of code:

if keys[pygame.K_LEFT]:
    is_facing_left = True
    movement_x -= tile_rect.width
    mapx -= 1
if keys[pygame.K_RIGHT]:
    is_facing_left = False
    movement_x += tile_rect.width
    mapx += 1
if keys[pygame.K_UP]:
    movement_y -= tile_rect.height
    mapy -= 1
if keys[pygame.K_DOWN]:
    movement_y += tile_rect.height
    mapy += 1

if mapx < 0:
    mapx = 0
    movement_x = 0
if mapx > world.get_width()-1 - map_tile_width:
    mapx = world.get_width()-1 - map_tile_width
    movement_x = 0
if mapy < 0:
    mapy = 0
    movement_y = 0
if mapy > world.get_height()-1 - map_tile_height:
    mapy = world.get_height()-1 - map_tile_height
    movement_y = 0

The full code is here if you'd like to see it:

https://github.com/DanPatWils/AdventureGame/blob/master/Almost


回答1:


You have multiple lines of the form mapx -= 1. You could use a variable outside of this loop that tracks your speed, and then you can use mapx -= current_speed to move your character. You can then modify your speed according to different conditions.

You should ensure your game's event loop and the map size are large enough, so that it does not look like your character is teleporting rather than running at high speed.



来源:https://stackoverflow.com/questions/53677741/pygame-character-movement-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!