Reputation: 11
So, I was exploring vectors in pygame, and decided to try and create some basic movement with it. I successfully am able to control my Rect, but the problem is that it leaves a trail behind it, similar to the snake game. I want only that single Rect from the very beginning to move without leaving trail marks. I've tried many different attempts at fixing this, but none worked. Please help me out, and explain where my mistakes are.
Bellow is my code for it
import pygame, sys
from pygame.math import Vector2
class PLAYER:
def __init__(self):
self.x = cell_size
self.y = cell_size
self.pos = Vector2(self.x, self.y)
self.direction = Vector2(0, 0)
def draw_player(self):
player_rect = pygame.Rect(int(self.pos.x * cell_size), int(self.pos.y * cell_size), cell_size, cell_size)
pygame.draw.rect(win, colors["GREEN"], player_rect)
def move_player(self):
self.pos += self.direction
class MAIN:
def __init__(self):
self.player = PLAYER()
def update(self):
self.player.draw_player()
self.player.move_player()
def collision(self):
pass
def gameover(self):
pass
pygame.init()
pygame.font.init()
# SCREEN SETUP
cell_size = 20
cell_number = 40
win = pygame.display.set_mode((cell_size * cell_number, cell_size * cell_number))
pygame.display.set_caption("Catch me")
icon = pygame.image.load("football.png")
pygame.display.set_icon(icon)
colors = {
"RED":(255, 0, 0),
"BLUE":(0, 0, 255),
"GREEN":(0, 255, 0),
}
SCREEN_UPDATE = pygame.USEREVENT
pygame.time.set_timer(SCREEN_UPDATE, 150)
game = MAIN()
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == SCREEN_UPDATE:
game.update()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
game.player.direction = Vector2(0, -1)
if event.key == pygame.K_DOWN:
game.player.direction = Vector2(0, 1)
if event.key == pygame.K_RIGHT:
game.player.direction = Vector2(1, 0)
if event.key == pygame.K_LEFT:
game.player.direction = Vector2(-1, 0)
pygame.display.update()
Upvotes: 1
Views: 65
Reputation: 210889
You must redraw the entire scene. Therfore, you must clear the display before you draw the new scene. You are actually drawing on a Surface
object (win
). Anything drawn on that surface stays there until you draw over it. Fill the entire display with a solid color using pygame.Surface.fill
before you draw the objects in the scene:
class MAIN:
# [...]
def update(self):
# clear the display
win.fill((0, 0, 0))
self.player.draw_player()
self.player.move_player()
Upvotes: 1