Neemaximo Neemaximo - 1 month ago 7
Python Question

Pygame moving an object

So I am trying to simply move an object in pygame. I have been looking up tutorials but all I can find is how to make it look like it is snowing, lol. I have been trying to implement that method into moving an object but I am having no luck. All I want to do is move an object across the screen and when it reaches the end of the screen it resets and goes again. So I am trying to move the object that I put in my code (the two polygons, line, and circle) across the screen, horizonally or vertically, doesnt really matter.

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)

pygame.draw.polygon(windowSurface,BLUE,((146, 0), (250, 100), (230, 265), (44, 250), (0,110)))
pygame.draw.polygon(windowSurface,RED,((70, 0), (150, 200), (0, 50)))
pygame.draw.line(windowSurface,BLACK,(60, 60), (120, 60), 8)
pygame.draw.circle(windowSurface, GREEN , (150,150), 15, 0)


pygame.display.update()

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

Answer

With your approach, you can't. The idea behind using pygame is to draw all the objects you want to draw each frame. You must move the drawing inside your while True loop first. Then, since you're drawing everything each frame, you could:

  • create object/variables for storing the position and direction of your object
  • check if the object is reaching one border of the screen
  • use the new position for drawing your polygon

So at the end, you could have something like that (it's your task to change to an object)

# ... pygame and app initialization

# get screen size
info = pygame.display.Info()
sw = info.current_w
sh = info.current_h

# initial position
x = y = 0
# initial direction
dx = 5
dy = 2

while True:

    # update position with direction
    x += dx
    y += dy

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

    # then draw and use x/y in your drawing instructions!
    # ... pygame events ...
Comments