文章出處
文章列表
pygame是用來寫2D游戲的。
實現斜線運動,無非是在x和y兩個方向上分運動的合成。x方向上的運動,當撞到邊界的時候取相反速度就好了。
這里是用網球王子中的圖片,以及一個網球實現,效果截圖:
注意看,那個方塊形狀的網球是會動的,撞到邊界就反彈,時刻勻速(這情況太理想了。。。)
代碼:
# coding:utf-8 bgimg = 'teni.jpg' spimg = 'ball.jpg' import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) bg = pygame.image.load(bgimg).convert() sp = pygame.image.load(spimg).convert_alpha() clock = pygame.time.Clock() x, y =100., 100. speed_x, speed_y = 133., 170. while True: for event in pygame.event.get(): if event.type == QUIT: exit() screen.blit(bg, (0, 0)) screen.blit(sp, (x, y)) time_passed = clock.tick(30) # 設定最大FPS不超過30 # FPS:Frame per second time_passed_seconds = time_passed / 1000.0 x += speed_x * time_passed_seconds y += speed_y * time_passed_seconds if x > 640 - sp.get_width(): speed_x = -speed_x x = 640 - sp.get_width() elif x < 0: speed_x = - speed_x x = 0. if y > 480 - sp.get_height(): speed_y = -speed_y y = 480 - sp.get_height() elif y < 0: speed_y = -speed_y y = 0 pygame.display.update()
文章列表
全站熱搜