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

極客小將

您現(xiàn)在的位置是:首頁 » python編程資訊

資訊內(nèi)容

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

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

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

上一節(jié)中我們學習并明白了什么是向量,向量之間如何進行計算。現(xiàn)在已經(jīng)有人為我們寫好了一個可以直接使用的向量類-》在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)
'''

那么向量道底有什么用,我們來看一個實戰(zhàn)的例子,這個程序實現(xiàn)的效果是魚不停的在鼠標周圍游動,若即若離,在沒有到達鼠標時,加速運動,超過以后則減速。因而魚會在鼠標附近晃動。

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
 
    # 參數(shù)前面加*意味著把列表或元組展開
    destination = Vec2d( *pygame.mouse.get_pos() ) - Vec2d( *sprite.get_size() )/2
    # 計算魚兒當前位置到鼠標位置的向量
    vector_to_mouse = destination - position
    # 向量規(guī)格化
    vector_to_mouse.normalized()

    # 這個heading可以看做是魚的速度,但是由于這樣的運算,魚的速度就不斷改變了
    # 在沒有到達鼠標時,加速運動,超過以后則減速。因而魚會在鼠標附近晃動。
    heading = heading + (vector_to_mouse * 0.001)    
 
    position += heading * time_passed_seconds
    pygame.display.update()

雖然這個例子里的計算有些讓人看不明白,但是很明顯heading的計算是關鍵,如此復雜的運動,使用向量居然兩句話就搞定了。


本站部分內(nèi)容轉載自網(wǎng)絡,如有侵權請聯(lián)系管理員及時刪除。

預約試聽課

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

主站蜘蛛池模板: 依兰县| 长治市| 青川县| 越西县| 延川县| 马公市| 岳阳市| 府谷县| 广灵县| 富锦市| 二手房| 吉木萨尔县| 定襄县| 霍林郭勒市| 射阳县| 玛曲县| 德惠市| 海南省| 鹤庆县| 北京市| 南漳县| 合水县| 新田县| 台江县| 灵川县| 台南县| 东乌珠穆沁旗| 安平县| 新余市| 前郭尔| 禄劝| 石景山区| 秀山| 钟山县| 巴林右旗| 闽侯县| 城口县| 宁陕县| 和田市| 右玉县| 固安县|