Slightjab
Slightjab

Reputation: 11

Pygame, Character Movement Speed

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

Upvotes: 1

Views: 818

Answers (1)

jdrd
jdrd

Reputation: 149

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.

Upvotes: 1

Related Questions