分享

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

 TOP收藏 2020-05-25

先上代码

  1. import pygame
  2. from pygame.locals import *
  3. from pygame.math import *
  4. import sys
  5. pygame.init()
  6. size = width, height = 1600, 900
  7. screen = pygame.display.set_mode(size)
  8. color = (0, 0, 0) # 设置颜色
  9. ball = pygame.image.load('dabai_new.gif')
  10. ballrect = ball.get_rect()
  11. sp = Vector2(0,0) #设置初始位置
  12. speed = 3.0
  13. clock = pygame.time.Clock()
  14. mouse_xy = (0,0)
  15. while True:
  16. clock_time = clock.tick_busy_loop(60)
  17. for event in pygame.event.get():
  18. if event.type == pygame.QUIT:
  19. sys.exit()
  20. elif event.type == pygame.MOUSEBUTTONDOWN:
  21. mouse_xy = Vector2(event.pos)#获取鼠标的向量
  22. dis = mouse_xy - sp
  23. dis_lenth = dis.length()#计算物体到鼠标点击处的距离
  24. if dis_lenth < speed: #做一个判断,如果距离小于速度,则不需要移动
  25. mouse_xy = sp
  26. elif dis_lenth != 0: #
  27. dis.normalize_ip() #坐标归一化非常重要
  28. dis = dis*speed #计算每一帧移动的坐标数
  29. sp += dis #叠加每次移动的坐标
  30. screen.fill(color)
  31. screen.blit(ball, sp)
  32. pygame.display.flip()

这个方案中最重要的就是坐标归一化,归一化之后长度永远为一,实际移动的坐标数就是帧数乘以速度的值

我把pygame.Vertor2中坐标归一化使用的公式列出来:

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约