我想了解get_rect()
如何工作。在這個簡單的例子中,我有兩個圖像,並希望獲得第二個圖像的位置並將第一個圖像移動到第二個圖像。pygame:如何正確使用get_rect()
我已經看了很多在線的例子,不能得到這個工作。我究竟做錯了什麼?
import pygame, sys
from pygame.locals import *
import time
pygame.init()
FPS = 10 # frames per second setting
fpsClock = pygame.time.Clock()
# Set up the window
DISPLAYSURF = pygame.display.set_mode((600, 400), 0, 32)
pygame.display.set_caption('Test program for get_rect()')
WHITE = (255, 255, 255)
# Load two images
baseImg = pygame.image.load('image1.jpg')
spaceshipImg = pygame.image.load('image2.jpg')
DISPLAYSURF.fill(WHITE)
# Place one image at the bottom of the screen
DISPLAYSURF.blit(baseImg, (300, 300))
pygame.display.update()
# Place the second image at the top of the screen
DISPLAYSURF.blit(spaceshipImg, (300, 0))
pygame.display.update()
# Wait for one second
time.sleep(1)
# Obtain the rectangle for each image
baseRect = baseImg.get_rect()
spaceshipRect = spaceshipImg.get_rect()
# This is where I believe I'm going wrong
# I understand this to obtain the x,y of the spaceship image
# Set the xy coordinates for the top image to the xy of the bottom image
spaceshipRect.x = baseRect.x
spaceshipRect.y = baseRect.y
# Move the top image to new xy position
# However this doesn't work
DISPLAYSURF.blit(spaceshipImg, (spaceshipRect.x, spaceshipRect.y))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
當您想知道某個函數的某些內容時,請在Python中使用'help()'命令或查找[documentation](https://www.pygame.org/docs/ref/surface.html# pygame.Surface.get_rect)。另外,提供你看過的例子,因爲它們都不應該提到它「獲得飛船圖像的x,y」。該文件說:_「這個矩形將始終從0,0」開始。 –