Reputation: 67
So I made this game in pygame and I want the player to move and it moves but not in the way I want it.It kinda teleports and then goes back to walking normally and then it teleports again and so on.
This is the code by now:
import pygame
pygame.init()
screen = pygame.display.set_mode((1000,1000))
clock = pygame.time.Clock()
playerX = 100
playerY = 100
def ecranAlb():
WHITE = [255,255,255]
screen.fill(WHITE)
def player():
global playerX, playerY
playerImg = pygame.image.load('knight.png')
playerImg = pygame.transform.scale(playerImg,(250,150))
screen.blit(playerImg,(playerX,playerY))
vel = 10
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
playerX -= vel
if keys[pygame.K_RIGHT]:
playerX += vel
if keys[pygame.K_UP]:
playerY -= vel
if keys[pygame.K_DOWN]:
playerY += vel
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
ecranAlb()
player()
clock.tick(200)
pygame.display.flip()
Upvotes: 1
Views: 161
Reputation: 210899
Do not load the image in the player
function. pygame.image.load
causes the lag, as it is very time consuming. Load the image once during initialization and us the loaded image inside the function.
Ensure that the image Surface has the same format as the display Surface. Use convert()
(or convert_alpha()
) to create a Surface that has the same pixel format. This improves performance when the image is blit
on the display, because the formats are compatible and blit
does not need to perform an implicit transformation.
playerImg = pygame.image.load('knight.png').convert_alpha()
playerImg = pygame.transform.scale(playerImg,(250,150))
vel = 10
def player():
global playerX, playerY
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
playerX -= vel
if keys[pygame.K_RIGHT]:
playerX += vel
if keys[pygame.K_UP]:
playerY -= vel
if keys[pygame.K_DOWN]:
playerY += vel
screen.blit(playerImg,(playerX,playerY))
Upvotes: 1