Having clock.tick() vs not having clock.tick()

Viewed 32

I am working on this simple game using pygame. I encountered this FPS thing using clock.tick() but I don't really understand it. If I have the line "clock.tick(45)", I press and hold the right arrow key, my spaceship will be moving smoothly toward the edge of the app but when I don't have that piece of code, I press the right arrow only once, my spaceship will go all the way to my application's edge without smooth movement. Can anyone explain why is it so? Thank you

`

import pygame

from Enemy import Enemy
from Spaceship import Spaceship

pygame.init()

TITLE = "GAME"
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 500
SPACESHIP_X = 0
SPACESHIP_Y = 400
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption(TITLE)
background = pygame.image.load("images\\spaceBackground.jpg").convert()

running = True

spaceShip = Spaceship()


def draw_window_and_object():

    screen.blit(background, (0,0))

    screen.blit(spaceShip.spaceShipObject, (SPACESHIP_X, SPACESHIP_Y))

    pygame.display.update()


def handle_movement(keys):
    global SPACESHIP_X
    if keys[pygame.K_RIGHT] and SPACESHIP_X < SCREEN_WIDTH - 50:
        SPACESHIP_X += 10
    if keys[pygame.K_LEFT] and SPACESHIP_X > 0:
        SPACESHIP_X -= 10


clock = pygame.time.Clock()

while running:
    clock.tick(50)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys_pressed = pygame.key.get_pressed()
    handle_movement(keys_pressed)
    draw_window_and_object()


pygame.quit()

`

1 Answers

tick(45) means 45 FPS (Frames Per Second) and this means that every frame (every loop) should take 22ms (1second = 1000ms, and 1000ms/45 gives 22ms).

But code may run (much) faster and every frame/loop may take different time - and without tick(45) you see frames in different moments and ship is not moving smoothly.

Using tick(45) it measures time in every frame/loop and it eventually sleeps/waits to take 22ms in every frame/loop.


BTW:

If you will run code without tick(45) on faster computer then ship will move faster.
If you use tick(45) then ship will move with the same speed on faster computers.

If game doesn't have fast action which needs to display many frames then using tick() you can reduce CPU usage.


Other method is to take time used by frame and use it to calculate distance for ship

dt = tick() # without value

SPACESHIP_X -= 10 * dt
Related