Tycho
Tycho

Reputation: 11

Issue in moving the rectangle up and down in pygame

I tried to move a rectangle in Pygame using arrow keys. I'm able to move it left and right but it does not move up and down. If i press the down key it grows in y direction rather than moving. Here's the code

    import pygame , sys
    from pygame.locals import *

    catx = 10
    caty = 10
    screen =0

    def myquit():
        pygame.quit()
        sys.exit()
    
    def event_input(events):
        global catx,caty, screen
    
        for event in events:
            if event.type == QUIT:
                pygame.quit()
            else:
                if event.type== KEYDOWN:
                    if event.key== K_ESCAPE:
                        myquit()
                    elif event.key== K_RIGHT:
                        catx+=5
                    elif event.key==K_LEFT:
                        catx-=5
                    else:
                        pass
                elif event.type== KEYUP:
                    if event.key== K_DOWN:
                        caty+=5
                    elif event.key== K_UP:
                        caty-=5
                screen.fill((0,0,0))
                pygame.draw.rect(screen,(255,255,255),(catx,50,50,caty))
                pygame.display.update()
    
    
    def main():
        global screen
        pygame.init()
        screen_width=640
        screen_height=500
        pygame.display.set_mode((screen_width,screen_height))
        pygame.display.set_caption("Move Rectangle")
        screen = pygame.display.get_surface()
        pygame.display.update()
    
        while True:
            event_input(pygame.event.get())
    
    main()

Upvotes: 1

Views: 143

Answers (1)

user12291970
user12291970

Reputation:

You are changing the height of the rectangle rather than the position. Arguments for pygame.rect are (x, y, width, height), but your arguments are passed as though the arguments were(x, width, height, y), so it changes the height of the rectangle rather than y. Replace line

pygame.draw.rect(screen,(255,255,255),(catx,50,50,caty))

with

pygame.draw.rect(screen,(255,255,255),(catx,caty,50,50))

Upvotes: 1

Related Questions