Skip to content Skip to sidebar Skip to footer

How To Continuously Move An Image Smoothly In Pygame?

Yes, I know that there are similar questions out there, and I have read through them, but they do not help me (or most likely I just don't understand them enough to use them). FYI:

Solution 1:

Do not "move" the image by 10, but move it by 1.

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

This method should be called once per frame.

That means that the loop:

var_x, var_bounce, speed_x = 0, 0, 2# application loop
clock = pygame.time.Clock()
run = Truewhile run:
    clock.tick(60)

    if var_bounce == 0:
        if var_x > -207:
            var_x = var_x - speed_x 
        else:
            var_bounce = 1elif var_bounce == 1:
        if var_x < 0:
            var_x = var_x + speed_x 
        else:
            var_bounce = 0# [...]

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 300))
clock = pygame.time.Clock()

background = pygame.Surface((window.get_width()+200, window.get_height()))
ts, w, h, c1, c2 = 100, *background.get_size(), (64, 64, 64), (127, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0else c2) for x inrange((w+ts-1)//ts) for y inrange((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

var_x, var_bounce, speed_x = 0, 0, 2defscroll():
    global var_x, var_bounce
    if var_bounce == 0:
        if var_x > -200:
            var_x = var_x - speed_x
        else:
            var_bounce = 1elif var_bounce == 1:
        if var_x < 0:
            var_x = var_x + speed_x
        else:
            var_bounce = 0

run = Falsewhilenot run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = True

    scroll()

    window.blit(background, (var_x, 0))
    pygame.display.flip()

pygame.quit()
exit()

Post a Comment for "How To Continuously Move An Image Smoothly In Pygame?"