很難知道你在這裏做錯了什麼,因爲你沒有發佈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)
附註:Python註釋##不是/ – abccd
每次更新'block_rect.x'時,都需要將它重新分配給'x'。與'y'一樣。這稱爲「按值傳遞」而不是「按引用傳遞」,因此它複製數字而不是引用正在更新的值。 –
你的位置更新代碼在哪裏? –