用python和pygame游戏编程入门-向量类的使用,python向量运算,


用python和pygame游戏编程入门-向量类的使用

上一节中我们学习并明白了什么是向量,向量之间如何进行计算。现在已经有人为我们写好了一个可以直接使用的向量类-》在Python3.x下可用的向量类源码

将代码保存到本地,并命名为Vec2d.py

有了这个类,我们就来编写一个简单得测试程序,看看效果:

from Vec2d import *A = Vec2d(10.0, 20.0)B = Vec2d(30.0, 35.0)C=Vec2d(-10, 5)AB = A+Bprint(AB.normalized())print ("Vector AB is", AB)print ("AB * 2 is", AB * 2)print ("AB / 2 is", AB / 2)print ("AB + (–10, 5) is", (AB +C))'''运行结果:Vector AB is Vec2d(40.0, 55.0)AB * 2 is Vec2d(80.0, 110.0)AB / 2 is Vec2d(20.0, 27.5)AB + (–10, 5) is Vec2d(30.0, 60.0)'''

那么向量道底有什么用,我们来看一个实战的例子,这个程序实现的效果是鱼不停的在鼠标周围游动,若即若离,在没有到达鼠标时,加速运动,超过以后则减速。因而鱼会在鼠标附近晃动。

background_image_filename = './img/Underwater.png'sprite_image_filename = './img/fish-b.png'import pygamefrom pygame.locals import *from sys import exitfrom Vec2d import * pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(background_image_filename).convert()sprite = pygame.image.load(sprite_image_filename).convert_alpha() clock = pygame.time.Clock() position = Vec2d(100.0, 100.0)heading = Vec2d(0,0) while True:     for event in pygame.event.get():        if event.type == QUIT:            exit()     screen.blit(background, (0,0))    screen.blit(sprite, position)        time_passed = clock.tick()    time_passed_seconds = time_passed / 1000.0     # 参数前面加*意味着把列表或元组展开    destination = Vec2d( *pygame.mouse.get_pos() ) - Vec2d( *sprite.get_size() )/2    # 计算鱼儿当前位置到鼠标位置的向量    vector_to_mouse = destination - position    # 向量规格化    vector_to_mouse.normalized()    # 这个heading可以看做是鱼的速度,但是由于这样的运算,鱼的速度就不断改变了    # 在没有到达鼠标时,加速运动,超过以后则减速。因而鱼会在鼠标附近晃动。    heading = heading + (vector_to_mouse * 0.001)         position += heading * time_passed_seconds    pygame.display.update()

虽然这个例子里的计算有些让人看不明白,但是很明显heading的计算是关键,如此复杂的运动,使用向量居然两句话就搞定了。


本站内容未经许可,禁止任何网站及个人进行转载。

评论关闭