2017-06-16 23 views
0

代碼:在pygame的,我需要設置的圖像的座標變量(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)」,就好像圖像位於窗口的左上角並且不會移動

我在做什麼錯誤?

+1

附註:Python註釋##不是/ – abccd

+0

每次更新'block_rect.x'時,都需要將它重新分配給'x'。與'y'一樣。這稱爲「按值傳遞」而不是「按引用傳遞」,因此它複製數字而不是引用正在更新的值。 –

+1

你的位置更新代碼在哪裏? –

回答

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) 
+0

我已經想通了,我忘了每幀更新位置,非常感謝您的幫助 –

相關問題