Neemaximo
Neemaximo

Reputation: 20841

Moving object across screen in Pygame

So I am trying to move this random jumble of two polygons, a circle, and a line across the screen, any direction, and when it reaches the end of the screen is is placed back on the screen and moves again. Simply put, I want to move those shapes across the screen. I cannot really figure out how, I am new to pygame so all this is a bit confusing but this is what I have so far.

import pygame, sys, time, random
from pygame.locals import *

pygame.init()

windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Paint")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

windowSurface.fill(WHITE)

info = pygame.display.Info()
sw = info.current_w
sh = info.current_h

x = y = 0

dx = 5
dy = 2


while True:

    pygame.draw.polygon(windowSurface,BLUE,((0+x,250+y),(120+x,120+y),(55+x,55+y)))
    pygame.draw.polygon(windowSurface,RED,((0+x,150+y),(85+x,85+y),(100+x,175+y),(0+x,150+y)))
    pygame.draw.line(windowSurface,BLACK,(60+x,85+y), (120+x, 110+x), 6)
    pygame.draw.circle(windowSurface, GREEN , (75+x,100+y), 13, 0)

    x += dx
    y += dy

    if x - dx < 0 or x + dx > sw:
        dx = -dx
    if y - dy < 0 or y + dy > sh:
        dy = -dy


    pygame.display.update()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

Upvotes: 1

Views: 7112

Answers (1)

c0m4
c0m4

Reputation: 4453

You probably want to clear the screen each time you redraw.

while True:
    windowSurface.fill(WHITE) #This clears the screen on each redraw
    pygame.draw.polygon(windowSurface,BLUE,((0+x,250+y),(120+x,120+y),(55+x,55+y)))
    pygame.draw.polygon(windowSurface,RED,((0+x,150+y),(85+x,85+y),(100+x,175+y),(0+x,150+y)))
    pygame.draw.line(windowSurface,BLACK,(60+x,85+y), (120+x, 110+y), 6)
    pygame.draw.circle(windowSurface, GREEN , (75+x,100+y), 13, 0)

Also, look at the coordinates for the line. I have changed the endpoint to (120+x, 110+y)

And if you change your edge detection to this your shapes will mostly stay in the window

if x < 0 or x > sw-120:
    dx = -dx
    x += dx
if y < -85 or y > sh-175:
    dy = -dy
    y += dy 

Upvotes: 2

Related Questions