代码:
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((display_width, display_height))
blockImg = pygame.image.load('Rectangle.png')
block_rect = blockImg.get.rect()
x = block_rect.x
/or x = block_rect.left/
y = block_rect.y
/or y = block_rect.top/
print(x, y)
问题
当我编写了一些代码以稳定的速率在屏幕上移动图像并不断更新图像的 x 和 y 时,它只会打印出"(0, 0(",就好像图像在窗口的左上角并且不移动一样
我做错了什么?
很难知道你在这里做错了什么,因为你没有发布 blit 代码。
如果我不得不猜测,您可能还没有更新您在向屏幕传送时使用的 x、y 变量。 它们不会自动更新,您必须设置
x = block_rect.left
每一帧。
但是,这里有一些最小的工作代码可以完成您的期望。
import pygame
BGCOLOR = (100,100,100)
SCREENWIDTH = 600
SCREENHEIGHT = 400
pygame.init()
display = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
clock = pygame.time.Clock()
block_img = pygame.image.load('Rectangle.png')
block_rect = block_img.get_rect()
#set velocity variable for updating position of rect
#make sure you do this before you go into the loop
velocity = 1
while 1:
#fill in display
display.fill(BGCOLOR)
#pygame event type pygame.QUIT is activated when you click the X in the topright
for event in pygame.event.get():
if event.type == pygame.QUIT:
#if you don't call pygame.quit() sometimes python will crash
pygame.quit()
#exit loop
break
#reverses velocity variable if rect goes off screen
if block_rect.right > SCREENWIDTH:
velocity = -velocity
elif block_rect.left < 0:
velocity = -velocity
#update blocks position based on velocity variable
block_rect.left += velocity
#variables representing the x, y position of the block
x, y = block_rect.left, block_rect.top
display.blit(block_img, (x,y))
#display.blit(block_img, block_rect) would also work here
pygame.display.flip()
clock.tick(60)