Home > Back-end >  How can I move a sprite in pygame?
How can I move a sprite in pygame?

Time:06-29

I want to make a golf game using pygame. Right now I was testing just moving the sprites around. Whenever I modify player.position the sprites get's copied and cut in half. I'm really confused.

A screenshot. The circle is the player sprite.

Here is my code so far:

import pygame
import player
import os

WIDTH, HEIGHT = 750, 750

WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("GOLF")

#Setting up the player
player = player.PlayerClass()

def draw_window ():
    #drawing the player
    WINDOW.blit(player.texture, player.position)

pygame.display.update()
def LeftClick ():
    #difference = player.position - pygame.mouse.get_pos()
    player.position.x  = 10

def main ():    
    run = True
    FPS = 60
    clock = pygame.time.Clock()

    while run:
        clock.tick(FPS)
    
        draw_window()
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    LeftClick()
main()

The player class:

import pygame
import os
class PlayerClass:
    def __init__(self):
        self.texture = pygame.image.load(os.path.join((os.path.join("assets", "imgs")), "ball.png"))
        self.position = pygame.Vector2(300, 500)

CodePudding user response:

You have to redraw the scene in every frame. Redraw means:

  • clear the display

  • draw the objects

  • update the display

def draw_window ():

    # clear display
    WINDOW.fill((0, 0, 0))

    # drawing the player
    WINDOW.blit(player.texture, player.position)

    # update display
    pygame.display.update()

Drawing on the display surface means nothing other than permanently changing the color of the pixel in the surface. Therefore the display needs to be cleared at the begin of every frame in the application loop. The typical PyGame application loop has to:

  • Related