Pygame中实现图像旋转效果-高级2-2
2.2.3 确定运动方向
之后通过math.atan2()方法计算飞船的运动方向,如图6所示。
图6 计算飞船运动方向的代码
由于math.atan2()方法的到的是弧度,需要通过math.degrees()方法将弧度转换为角度。相关链接2 math.atan2()方法的详细用法请参考《Pygame中实现图像旋转效果-中级》。
2.2.4 根据运动方向旋转飞船图片
通过图7所示代码,根据运动方向旋转飞船图片。
图7 根据运动方向旋转飞船图片的代码
其中,spacecraft_rotate为旋转之后的飞船图片。
相关链接3 图7中pygame.transform.rotate()旋转的角度是-spacecraft_rangled的原因,请参考《Pygame中实现图像旋转效果-中级》。
2.2.5 飞船上一时刻位置的更新
在确定了飞船在当前位置的运动方向之后,需要把飞船上一时刻的位置更新为当前位置,以便确定下一时刻的运动方向,代码如图8所示。
图8 飞船上一时刻位置更新的代码
2.3 确定飞船位置的代码实现
从图3中可以看出,飞船当前位置是(spacecraft_pos_x, spacecraft_pos_y),这两个白能量已经在图4所示的代码中确定,此时只需要将其设置为飞船显示区域的中心位置即可,代码如图9所示。
图9 确定飞船位置的代码
其中,spacecraft_rotate_rect即为旋转后的图片要显示的矩形范围,将其center设置为(spacecraft_pos_x, spacecraft_pos_y),就可以确定飞船的当前位置了。
注意1 图1所示的星球旋转的实现,可参考《Pygame中实现图像旋转效果-初级》。
注意2 飞船与星球图片的导入及显示,与《Pygame中实现图像旋转效果-初级》中的原理相同。
3 完整代码
完整代码如下所示。
import pygame
import math
from sys import exit
from pygame.locals import *pygame.init()
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
space = pygame.image.load('space.png').convert_alpha()spacecraft = pygame.image.load('freelance.png').convert_alpha()
spacecraft = pygame.transform.smoothscale_by(spacecraft, (0.5, 0.5))
spacecraft_radius = 250
spacecraft_pos_x, spacecraft_pos_y = 0, 0
spacecraft_prepos_x, spacecraft_prepos_y = 0, 0
spacecraft_speed = 0.02plane = pygame.image.load('planet2.png').convert_alpha()
plane_center_pos = (screen_width//2, screen_height//2)
plane_angle = 0.0
plane_speed = 0.1angle = 180.0#确定飞船位置
clock = pygame.time.Clock()while True:for event in pygame.event.get():if event.type == QUIT:pygame.quit()exit()screen.blit(space, (0, 0))#星球旋转plane_angle = (plane_angle+plane_speed)%360plane_rotate = pygame.transform.rotate(plane, -plane_angle)plane_rect = plane_rotate.get_rect(center=plane_center_pos)screen.blit(plane_rotate, plane_rect)#飞船旋转angle = (angle+spacecraft_speed)%360spacecraft_pos_x = plane_center_pos[0] + spacecraft_radius*math.cos(angle)spacecraft_pos_y = plane_center_pos[1] + spacecraft_radius*math.sin(angle)spacecraft_pos_deltax = spacecraft_pos_x - spacecraft_prepos_xspacecraft_pos_deltay = spacecraft_pos_y - spacecraft_prepos_yspacecraft_rangle = math.atan2(spacecraft_pos_deltay, spacecraft_pos_deltax)spacecraft_rangled = math.degrees(spacecraft_rangle)spacecraft_rotate = pygame.transform.rotate(spacecraft, -spacecraft_rangled)spacecraft_rotate_rect = spacecraft_rotate.get_rect(center=(spacecraft_pos_x, spacecraft_pos_y))spacecraft_prepos_x = spacecraft_pos_xspacecraft_prepos_y = spacecraft_pos_yscreen.blit(spacecraft_rotate, spacecraft_rotate_rect)pygame.display.flip()clock.tick(60)