[英].get_rect() and .move IN pygame
我正在嘗試用 pygame 做一個簡單的球運動代碼。
在我的循環中,我寫道:
ballrect = ballrect.move([2,0])
將球向右移動
if((ballrect.left<0) or (ballrect.right>width)): speed[0]= -speed[0]
當球“擊中”水平邊緣時反轉速度
if((ballrect.top<0) or (ballrect.bottom>height)): speed[1] = -speed[1]
當球“擊中”垂直邊緣時反轉速度
if((ballrect.left==width/2)): speed[0]=0; speed[1]=2
if((ballrect.left==width/2)): speed[0]=0; speed[1]=2
當我的球到達顯示器的中間時,它會停止水平移動並開始垂直移動。
但是當我的圖像底部達到垂直邊緣(ballrect.bottom>height)時,如果要反轉垂直速度,它不會進入第二個。 為什么?
完整代碼:
import sys, pygame
pygame.init()
size = width, height = 1000, 1000
speed = [2,0]
black = 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load(r"C:\Users\Victor\Desktop\bolinha_de_gorfe.png")
ballrect = ball.get_rect()
while(1):
for event in pygame.event.get():
if(event.type==pygame.QUIT): sys.exit()
ballrect = ballrect.move(speed)
if((ballrect.left<0) or (ballrect.right>width)):
speed[0]= -speed[0]
if((ballrect.top<0) or (ballrect.bottom>height)):
speed[1] = -speed[1]
if((ballrect.left==width/2)):
speed[0]=0
speed[1]=2
screen.fill((0,0,100))
screen.blit(ball,ballrect)
pygame.display.flip()
一旦球擊中中央屏幕,如果您的if
條件(ballrect.left==width/2)
始終為真,那么speed[1]=2
總是被重新設置。 因此,即使方向發生變化,該變化也會在以后被覆蓋。
解決這個問題的一種方法是將球移動 1 個像素,這樣它就不會一直觸發“在中間轉身”子句:
if ( ballrect.left==width/2 ):
speed[0]=0
speed[1]=2
ballrect.left = (width//2)-1 # 1 pixel off, so we don't re-trigger
或者你可以設置一個 boolean 標志來指示是否轉彎:
turned_already = False
...
if ( ballrect.left==width/2 and not turned_already ):
speed[0]=0
speed[1]=2
turned_already = True
您可能希望為您的代碼添加每秒幀數限制。 它可以更容易地看到球的運動(而不是整個事情在一瞬間結束)。
clock=pygame.time.Clock() # <<-- HERE
while(1):
for event in pygame.event.get():
if(event.type==pygame.QUIT):
sys.exit()
ballrect = ballrect.move(speed)
if((ballrect.left<0) or (ballrect.right>width)):
speed[0]= -speed[0]
if((ballrect.top<0) or (ballrect.bottom>height)):
speed[1] = -speed[1]
if ( ballrect.left==width/2 ):
speed[0]=0
speed[1]=2
ballrect.left = (width//2)-1 # 1 pixel off, so we don't re-trigger
screen.fill((0,0,100))
screen.blit( ball, ballrect )
pygame.display.flip()
clock.tick_busy_loop( 60 ) # <<-- AND HERE
這將幀更新限制為每秒 60 幀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.