Pygame中鼠標點擊之后,物體逐漸移動到鼠標點擊坐標的方法


 1 import pygame
 2 from pygame.locals import *
 3 from pygame.math import *
 4 import sys
 5  
 6 pygame.init()  
 7 size = width, height = 1600, 900 
 8 screen = pygame.display.set_mode(size)  
 9 color = (0, 0, 0)  # 設置顏色
10 ball = pygame.image.load('dabai_new.gif')  
11 ballrect = ball.get_rect()
12 sp = Vector2(0,0) #設置初始位置
13 speed = 3.0
14 clock = pygame.time.Clock()
15 mouse_xy = (0,0)
16 while True:
17     clock_time = clock.tick_busy_loop(60)
18     for event in pygame.event.get():  
19         if event.type == pygame.QUIT:  
20             sys.exit()
21         elif event.type == pygame.MOUSEBUTTONDOWN:
22             mouse_xy = Vector2(event.pos)#獲取鼠標的向量
23     dis = mouse_xy - sp 
24     dis_lenth = dis.length()#計算物體到鼠標點擊處的距離        
25     if dis_lenth < speed: #做一個判斷,如果距離小於速度,則不需要移動
26         mouse_xy = sp
27     elif dis_lenth != 0: #
28         dis.normalize_ip() #坐標歸一化非常重要
29         dis = dis*speed #計算每一幀移動的坐標數
30         sp += dis       #疊加每次移動的坐標
31  
32     screen.fill(color)  
33     screen.blit(ball, sp) 
34     pygame.display.flip()

這個方案中最重要的就是坐標歸一化,歸一化之后長度永遠為一,實際移動的坐標數就是幀數乘以速度的值

我把pygame.Vertor2中坐標歸一化使用的公式列出來:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM