Home > database >  How can I move my image slowly using pygame
How can I move my image slowly using pygame

Time:10-30

ive put the speed to be 1 but still the image moves very fast when i use the keys, code is given below. I want my image to slow down and how do I do this. I also am not using the groupsingle because atm I don't require multiple spirte groups

import pygame

# normal setup
pygame.init()
screen = pygame.display.set_mode((700, 700), pygame.RESIZABLE)
pygame.display.set_caption('ZAP!')
icon = pygame.image.load('download.jpg')
pygame.display.set_icon(icon)
clock = pygame.time.Clock()  # for framerate, not needed for my game cuz 2d
running = True  # while loop running so after ending game i can still run

# bg
bg = pygame.image.load('ok_proper.jpg')
bg_pic = pygame.transform.scale(bg, (700, 700))


class Spaceship(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('Graphics/spaceship.png')
        self.rect = self.image.get_rect(bottomleft=(250, 700))
        self.speed = 1

    def movement(self):
        keys = pygame.key.get_pressed()
        if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and self.rect.right   self.speed < 699:
            self.rect.x  = self.speed
        elif (keys[pygame.K_LEFT] or keys[pygame.K_a]) and self.rect.x - self.speed > 0:
            self.rect.x -= self.speed

    def update(self):
        self.movement()

# spaceship
spaceship = Spaceship()
# spaceship = pygame.sprite.GroupSingle()
# spaceship.add(Spaceship())


while running:
    screen.blit(bg_pic, (0, 0))  # background
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.blit(spaceship.image,spaceship.rect)
    spaceship.update()
    # spaceship.draw(screen)
    pygame.display.update()

I tried to reduce the self.speed in float but it just broke the game

CodePudding user response:

You have to limit the frames per second with pygame.time.Clock.tick. e.g.:

clock = pygame.time.Clock()

while running:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    spaceship.update()

    screen.blit(bg_pic, (0, 0))  # background
    screen.blit(spaceship.image, spaceship.rect)
    pygame.display.update()

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 following loop runs 60 times per second.:

clock = pygame.time.Clock()
run = True
while run:
    clock.tick(60)
  • Related