先上代码
- 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中坐标归一化使用的公式列出来:
联系客服