国产日韩欧美一区二区三区综合,日本黄色免费在线,国产精品麻豆欧美日韩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人預約都是免費的,你也試試吧...

主站蜘蛛池模板: 来宾市| 海南省| 许昌市| 贡嘎县| 抚远县| 高淳县| 金阳县| 淅川县| 巍山| 平潭县| 沙湾县| 油尖旺区| 公主岭市| 汶川县| 梧州市| 张家港市| 蛟河市| 蓬溪县| 伊通| 肥西县| 镇安县| 称多县| 纳雍县| 安新县| 镇赉县| 洛阳市| 龙山县| 鄱阳县| 津市市| 西昌市| 曲麻莱县| 皮山县| 南昌市| 澜沧| 武夷山市| 富川| 泉州市| 留坝县| 张家港市| 洛阳市| 安图县|