如题,声明:只为我个人做记录,不供参考,欢迎批评指正。
目的:实现类似重力作用的效果。
想法:按空格使小球有一个向上的速度。(只按一次空格)最终效果应为:先减速向上运动,后加速向下运动。
造成卡顿的代码如下:
import pygameimport sysfrom pygame.locals import *pygame.init()size = width, height = (1200, 600) screen = pygame.display.set_mode(size) screen.fill((255, 251, 240))bird = pygame.image.load('./images/1.png').convert_alpha()# 一个球,背景透明的图片bird_rect = bird.get_rect()bird_w, bird_h=bird_rect.width,bird_rect.heightbird_rect.x= 80bird_rect.y = 300move_y = 1y_bool = Truewhile True: if move_y < 1: move_y += 0.002 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys_pressed = pygame.key.get_pressed() if keys_pressed[K_SPACE] and y_bool: move_y = -0.7 y_bool = False elif not keys_pressed[K_SPACE]: y_bool = True if bird_rect.top > height - bird_h: # 到底端 bird_rect.top = height - bird_h elif bird_rect.top < 0: # 到顶端 bird_rect.top = 0 move_y = 0 bird_rect.top += move_y screen.fill((255, 251, 240)) screen.blit(bird, (bird_rect.left, bird_rect.top)) pygame.display.update()
效果如图所示:
卡顿;运行不流畅;并没有预想中的加速向下;向上运动时减速到0时会停顿长时间
而不用rect记录位置等的代码如下:
import pygameimport sysfrom pygame.locals import *import cv2def get_img_width_hight(img_name1): img1 = cv2.imread(img_name1) size1 = img1.shape return size1[1], size1[0]pygame.init()size = width, height = (1200, 600)screen = pygame.display.set_mode(size)screen.fill((255, 251, 240))bird_w, bird_h = get_img_width_hight('./images/1.png')bird = pygame.image.load('./images/1.png').convert_alpha()bird_x= 80bird_y = 300move_y = 1y_bool = Truewhile True: if move_y < 1: move_y += 0.002 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys_pressed = pygame.key.get_pressed() if keys_pressed[K_SPACE] and y_bool: move_y = -0.7 y_bool = False elif not keys_pressed[K_SPACE]: y_bool = True if bird_y > height - bird_h: # 到底端 bird_y = height - bird_h elif bird_y < 0: # 到顶端 bird_y = 0 move_y = 0 bird_y += move_y screen.fill((255, 251, 240)) screen.blit(bird, (bird_x, bird_y)) pygame.display.update()
运行效果如下:
流畅,实现预想中的重力作用
不知为何用rect记录就会卡顿
(当然可能是我的电脑问题)