Pygame中鼠标点击之后,物体逐渐移动到鼠标点击坐标的方法

时间:2020-01-09
本文章向大家介绍Pygame中鼠标点击之后,物体逐渐移动到鼠标点击坐标的方法,主要包括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中坐标归一化使用的公式列出来:

原文地址:https://www.cnblogs.com/orange-wrj/p/12172410.html