After Pygame mouse click, the object is gradually moved to the coordinates of the mouse click method

 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.length dis_lenth () # calculates the distance to the object of the mouse clicks         
25      IF dis_lenth <Speed: # to make a judgment, if the distance is less than the speed, the need to move 
26 is          mouse_xy = SP
 27      elif dis_lenth = 0:! #
 28          DIS .normalize_ip () # coordinate normalization important 
29          DIS DIS * Speed = # calculates the number of coordinates of each movable frame 
30          SP + DIS =        # superimposed each movement coordinate 
31 is   
32      screen.fill (Color)  
 33 is      screen.blit (Ball, SP) 
 34 is      pygame.display.flip ()

The most important aspect is the normalized coordinates, length after normalization is always one, the value of the actual movement of the coordinate data is multiplied by the speed of frames

I pygame.Vertor2 coordinate normalized using the formula listed:

Guess you like

Origin www.cnblogs.com/orange-wrj/p/12172410.html