Will Jones
Will Jones

Reputation: 1

Why is my rectangle is not moving down in pygame

When I am pressing the s-key my character that is represented by player 1 is not moving down. It could be that you cannot move the rectangles but I can't find anything to suggest that.

Also, the print function is just there to make sure that the key pressing is being registered

# Imports the packages need
import pygame
pygame.init()

# Sets height and width for the game window.
Width, Height = 700,500
WIN = pygame.display.set_mode((Width, Height))

VEL = 5
FPS = 60

player1 = pygame.draw.rect(WIN, (255, 255, 255), (10, 10, 10, 50))
player2 = pygame.draw.rect(WIN, (255, 255, 255), (680, 10, 10, 50))

def player1_control():  # Help needed!
    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_s]:
        player1.y -= (VEL)
        print ("registered")
    pygame.display.update()

def main(): # Opens the window and combines all the other functions.
    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        player1_control()
        pygame.display.update()

Upvotes: 0

Views: 118

Answers (1)

Rabbid76
Rabbid76

Reputation: 211258

You have to draw the rectangles in every frame:

player1 = pygame.Rect(10, 10, 10, 50)
player2 = pygame.Rect(680, 10, 10, 50)

def player1_control():
    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_s]:
        player1.y -= VEL

def main(): 
    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        player1_control()

        WIN.fill(0)
        pygame.draw.rect(WIN, (255, 255, 255), player1)
        pygame.draw.rect(WIN, (255, 255, 255), player2)
        pygame.display.update()

Note, pygame.draw.rect only draws a rectangle on the screen. pygame.Rect represents a rectangular objet. pygame.draw.rect returns a rect bounding the changed pixels.

Upvotes: 1

Related Questions