先上代码
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