Pygame moving an object

纵饮孤独 提交于 2021-02-19 06:29:10

问题


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()

回答1:


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 ...



回答2:


In order to do what you are trying to do, you will have to have something changing withing the "while True:" loop. Here is an example of a code that will do what you are trying to do:

import pygame, sys, pygame.locals#1
pygame.init()#2
window=pygame.display.set_mode((500, 400), 0, 32)#3
pygame.display.set_caption("Paint")#4
BLACK = (0, 0, 0)#5
WHITE = (255, 255, 255)#6
RED = (255, 0, 0)#7
GREEN = (0, 255, 0)#8
BLUE = (0, 0, 255)#9
pentagon=pygame.Surface((250, 265))#10
pentagon.fill((0, 0, 0))#11
pygame.draw.polygon(pentagon, BLUE, ((146, 0), (250, 100), (230, 265), (44, 250), (0,110)))#12
pentagon.set_colorkey((0, 0, 0))#13
triangle=pygame.Surface((150, 200))#14
triangle.fill((0, 0, 0))#15
pygame.draw.polygon(triangle, RED, ((70, 0), (150, 200), (0, 50)))#16
triangle.set_colorkey((0, 0, 0))#17
line=pygame.Surface((60, 8))#18
line.fill(BLACK)#19
circle=pygame.Surface((30, 30))#20
circle.fill((0, 0, 0))#21
pygame.draw.circle(circle, GREEN , (15, 15), 15, 0)#22
circle.set_colorkey((0, 0, 0))#23
rects={'pentagon': pentagon.get_rect(), 'triangle': triangle.get_rect(), 'line': line.get_rect(), 'circle': circle.get_rect()}#24
rects['line'].centery=60#25
rects['line'].left=60#26
rects['circle'].centerx=150#27
rects['circle'].centery=150#28
while True:#29
    for event in pygame.event.get():#30
        if event.type==pygame.locals.QUIT:#31
            pygame.quit()#32
            sys.exit()#33
    for rect in rects:#34
        rects[rect].right+=1#35
        if rects[rect].right>500:#36
            if rect=='line':#37
                rects['line'].centery=60#38
                rects['line'].left=60#39
            elif rect=='circle':#40
                rects['circle'].centerx=150#41
                rects['circle'].centery=150#42
            else:#43
                rects[rect].topleft=(0, 0)#44
    window.fill(WHITE)#45
    window.blit(pentagon, rects['pentagon'])#46
    window.blit(triangle, rects['triangle'])#47
    window.blit(line, rects['line'])#48
    window.blit(circle, rects['circle'])#49
    pygame.time.Clock().tick(40)#50
    pygame.display.update()#51

I will do my best to explain this code as well as possible.

Lines 1-9, you already know.

Line 10 begins with something you probably don't know about. Surface objects are a type of rectangular picture which can be attached to any other surface, or be drawn on with pygame.draw. Believe it or not, the window is actually a surface.

Line 10 creates a surface, line 11 fills it with black, and line 12 draws a pentagon on it.

Line 13 basically makes all pixels which are colored black transparent.

Lines 14-17, you should now understand.

Line 18 creates a new surface object for the line, but instead of drawing the line on it, it is filled with black and left alone. This is because, if you look at the line in your old program, you can see that it is really just a rectangle and nothing else.

Lines 20-23 you should understand.

Line 24 makes a dictionary of rectangles. Rectangles show the location of a surface object and are necessary in order to draw them onto anything.

Lines 25-28 change the location of the line and the circle. The reason I did this was because I thought you might like it considering that you don't have the line and the circle in the upper left hand corner in your program.

Lines 29-33 you should understand.

Line 34 starts a for loop which will go through all of the rects.

Line 35 moves the right of each of the rects one pixel to the right.

Line 36 checks to see if the right of the rect has hit the right edge of the window.

Line 37 checks to see if the one that hit the side is the line, and if it is, lines 38-39 move it to the location where you had it.

Line 40 checks to see if the one that hit the side is the circle, and if it is, lines 41-42 move it to the location where you had it.

Lines 43-44 put the rectangle in the top left corner, where the other two shapes started.

Line 45 you should know.

Lines 46-49 use the surface.blit() function. The first argument for this function is a surface, and the second is a rect.

Line 50 doesn't allow any more than 40 frames to pass in a second.

Line 51 updates the screen.

I really hope this helped, and I would appreciate it if you voted up or accepted my answer, considering how long it took me to write it. If you have any questions, please ask. Thank you!




回答3:


It isn't that difficult at all. First we'll be solving your problem on moving your object(s):

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)

x, y = 250, 200

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

    pressed = pygame.key.get_pressed()
    if pressed[K_UP]: y - 5
    if pressed[K_DOWN]: y + 5
    if pressed[K_LEFT]: x - 5
    if pressed[K_RIGHT]: x + 5

    pygame.display.update()

pygame.draw.polygon(windowSurface,BLUE,((x - 104, y - 200), (x, y - 100), (x - 20, y + 65), (x - 206, y + 50), (x - 250, y - 90)))
pygame.draw.polygon(windowSurface,RED,((x - 180, y - 200), (x - 100, y), (x - 250, y - 150)))
pygame.draw.line(windowSurface,BLACK,(x - 190, y - 140), (x - 130, y - 140), 8)
pygame.draw.circle(windowSurface, GREEN , (x - 100, y - 50), 15, 0)

In the above lines of code, all the coordinates are converted into a form of x,y variables. When the arrow keys are pressed, changes are made to the variables, thus altering the coordinates and positions of your shapes.




回答4:


This is a very good tutorial, it even includes some code very similar to yours for a start on basic graphics

http://inventwithpython.com/chapter17.html



来源:https://stackoverflow.com/questions/8441432/pygame-moving-an-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!