打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

先上代码

  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中坐标归一化使用的公式列出来:

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
秒会Pygame:键盘移动和鼠标点击移动物体的方法(含完整的代码)
散点图的xy怎么调整
程序员奶爸必修课——用 pygame 写小游戏
Unity3d中使用鼠标拖动物体移动
Pygame 入门
【新提醒】【渐开找怪或采集】圆+椭圆+方形+多点找色思路
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服