结合前面的贝塞尔曲线的实现方式,在enemyplane.py文件里添加
def set_BSpline_path(self,points):
self.path_type = 'BSpline'
self.points = points
data = np.array(points)
tck,u = interpolate.splprep(data.transpose(), s=0)
t = 1 / self.max_point
unew = np.arange(0, 1.01, t)
out = interpolate.splev(unew, tck)
self.path_points=out
使得self.path_points的点为运算后的点,值得注意的是,out的数组形式是out[0]保存的是一组x值,out[1]保存的是一组y值。
所以在update()函数里,点的传递方式为out[0][],out[1][]
elif self.path_type == 'BSpline':
if self.current_point == self.max_point:
self.current_point = 0
self.rect.x = self.path_points[0][self.current_point]
self.rect.y = self.path_points[1][self.current_point]
self.current_point += 1
和贝塞尔曲线点的传递方式不同,贝塞尔曲线里点的(x,y)形式存在的,点的传递方式为point[][0],point[][1]
if self.path_type == 'bezier':
if self.current_point == self.max_point:
self.current_point = 0
# print(self.path_points[self.current_point][0])
self.rect.x = self.path_points[self.current_point][0]
self.rect.y = self.path_points[self.current_point][1]
self.current_point += 1
在enemyuint.py里新建一个类,画个8字玩玩。
class BEnemyUnit(pygame.sprite.Sprite):
def __init__(self):
self._layer = 2
self.groups = allgroup, enemygroup
pygame.sprite.Sprite.__init__(self, self.groups)
self.image = pygame.image.load('./images/enemy/enemy0.png')
self.rect = self.image.get_rect()
#计数器
self.count = 0
#设置飞机出现间隔用
self.interval = 1000
self.start_time = pygame.time.get_ticks()
#用了sprite必须有个image ,用了个投机的办法,放到屏幕外面去了。
self.set_pos(-300,-300)
#控制飞行轨迹的点
self.points = [(400, -20), (200, 200), (400, 400), (600, 600),(400,800),(200,600),(400,400),(600,200),(200,-200)]
def set_pos(self,x,y):
self.rect.x = x
self.rect.y = y
def update(self):
cur_time = pygame.time.get_ticks()
if cur_time - self.start_time < self.interval:
return
self.start_time = cur_time
enemy = EnemyPlane()
enemy.set_BSpline_path(self.points)
enemy.set_pos(400,-20)
self.count +=1
#大于16架,就退出了
if self.count > 15:
self.kill()
main.py里,初始化函数里添加
benemyunit = BEnemyUnit()
运行效果如下:
全部资源及代码见链接
https://gitee.com/hailler/enemy/tree/master