这里涉及的到图像旋转后,方向的计算。我也不是很明白。先记录下来再说。
#_*_coding:utf-8 _*_import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 from math import *background_image_filename='./images/sea.jpg' sprite_image_filename='./images/fish.png'import pygame from pygame.locals import * from sys import exit pygame.init() # 让pygame完全控制鼠标 pygame.mouse.set_visible(False) pygame.event.set_grab(True)screen=pygame.display.set_mode((640,480),0,32) background=pygame.image.load(background_image_filename).convert() sprite=pygame.image.load(sprite_image_filename) clock=pygame.time.Clock()sprite_pos = Vector2(200, 150) # 初始位置 sprite_speed = 300. # 每秒前进的像素数(速度) sprite_rotation = 0. # 初始角度 sprite_rotation_speed = 360. # 每秒转动的角度数(转速)while True:for event in pygame.event.get():if event.type == QUIT:exit()pressed_keys = pygame.key.get_pressed()rotation_direction = 0.movement_direction = 0.# 通过移动偏移量计算转动rotation_direction = pygame.mouse.get_rel()[0]/5.0#更改角度if pressed_keys[K_LEFT]:rotation_direction+=1if pressed_keys[K_RIGHT]:rotation_direction-=1#前进 后退if pressed_keys[K_UP]:movement_direction+=1if pressed_keys[K_DOWN]:movement_direction-=1screen.blit(background,(0,0))#获得一条转向后的鱼rotated_sprite=pygame.transform.rotate(sprite,sprite_rotation)#获得转向后的矩形w,h=rotated_sprite.get_size()sprite_draw_pos=Vector2(sprite_pos.x-w/2,sprite_pos.y-h/2)screen.blit(rotated_sprite,sprite_draw_pos)time_passed = clock.tick()time_passed_seconds = time_passed / 1000.0# 图片的转向速度也需要和行进速度一样,通过时间来控制sprite_rotation += rotation_direction * sprite_rotation_speed * time_passed_seconds# 获得前进(x方向和y方向),这两个需要一点点三角的知识heading_x = sin(sprite_rotation * pi / 180.)heading_y = cos(sprite_rotation * pi / 180.)# 转换为单位速度向量heading = Vector2(heading_x, heading_y)# 转换为速度heading *= movement_directionsprite_pos += heading * sprite_speed * time_passed_secondspygame.display.update()