国产日韩欧美一区二区三区综合,日本黄色免费在线,国产精品麻豆欧美日韩ww,色综合狠狠操

極客小將

您現在的位置是:首頁 » python編程資訊

資訊內容

用python和pygame游戲編程入門-向量類的使用

極客小將2020-10-28-
上一節中我們學習并明白了什么是向量,向量之間如何進行計算。現在已經有人為我們寫好了一個可以直接使用的向量類-》在Python3.x下可用的向量類源碼

用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+B
print(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 pygame
from pygame.locals import *
from sys import exit
from 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的計算是關鍵,如此復雜的運動,使用向量居然兩句話就搞定了。


本站部分內容轉載自網絡,如有侵權請聯系管理員及時刪除。

預約試聽課

已有385人預約都是免費的,你也試試吧...

主站蜘蛛池模板: 娱乐| 威海市| 武山县| 沅陵县| 三台县| 江都市| 温州市| 富宁县| 如东县| 武宁县| 梁河县| 新兴县| 昌邑市| 北安市| 邹城市| 丰县| 仁怀市| 从化市| 绵竹市| 钦州市| 林西县| 湖州市| 神木县| 保山市| 井陉县| 老河口市| 阳城县| 五河县| 双牌县| 宁海县| 大连市| 枣强县| 盖州市| 巴马| 贡觉县| 惠来县| 苗栗市| 专栏| 集贤县| 民乐县| 尤溪县|