先上代碼
import pygame
from pygame.locals import *
from pygame.math import *
import sys
pygame.init()
size = width, height = 1600, 900
screen = pygame.display.set_mode(size)
color = (0, 0, 0) # 設置顏色
ball = pygame.image.load('dabai_new.gif')
ballrect = ball.get_rect()
sp = Vector2(0,0) #設置初始位置
speed = 3.0
clock = pygame.time.Clock()
mouse_xy = (0,0)
while True:
clock_time = clock.tick_busy_loop(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_xy = Vector2(event.pos)#獲取鼠標的向量
dis = mouse_xy - sp
dis_lenth = dis.length()#計算物體到鼠標點擊處的距離
if dis_lenth < speed: #做一個判斷,如果距離小於速度,則不需要移動
mouse_xy = sp
elif dis_lenth != 0: #
dis.normalize_ip() #座標歸一化非常重要
dis = dis*speed #計算每一幀移動的座標數
sp += dis #疊加每次移動的座標
screen.fill(color)
screen.blit(ball, sp)
pygame.display.flip()
這個方案中最重要的就是座標歸一化,歸一化之後長度永遠爲一,實際移動的座標數就是幀數乘以速度的值
我把pygame.Vertor2中座標歸一化使用的公式列出來: