[英]In PyGame, I need to set the coordinates of an image as variables (x, y)
码:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.