先上代码
from pygame.locals import * from pygame.math import * size = width, height = 1600, 900 screen = pygame.display.set_mode(size) ball = pygame.image.load('dabai_new.gif') ballrect = ball.get_rect() sp = Vector2(0,0) #设置初始位置 clock = pygame.time.Clock() clock_time = clock.tick_busy_loop(60) for event in pygame.event.get(): if event.type == pygame.QUIT: elif event.type == pygame.MOUSEBUTTONDOWN: mouse_xy = Vector2(event.pos)#获取鼠标的向量 dis_lenth = dis.length()#计算物体到鼠标点击处的距离 if dis_lenth < speed: #做一个判断,如果距离小于速度,则不需要移动 dis.normalize_ip() #坐标归一化非常重要 dis = dis*speed #计算每一帧移动的坐标数
这个方案中最重要的就是坐标归一化,归一化之后长度永远为一,实际移动的坐标数就是帧数乘以速度的值
我把pygame.Vertor2中坐标归一化使用的公式列出来:
|