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()