• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

python - How to rotate an image(player) to the mouse direction?

[复制链接]
菜鸟教程小白 发表于 2022-4-23 21:06:12 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

Im thinking about making a 2d shooting game in pygame and i want to make my player(Player_1) point to the mouse direction.I looked for a solution for hours and tried all solution i could find but none had worked so can you pls help me ? Here's my code:


This is my player(Player_1)

I will really appreciate all help.



Best Answer-推荐答案


You have to compute the angle of the vector from the player to the mouse. get the mouse position by pygame.mouse.get_pos() and the rectangle (pygame.Rect) around the player:


Calculate the vector from the player to the mouse and compute the angle of vector by math.atan2. The y-axis needs to be reversed (-dy) as the y-axis is generally pointing up, but in the PyGame coordinate system the y-axis is pointing down.


In addition, a correction angle must be deducted (- correction_angle). The correction angle depends on the Sprite. If the Sprite

is looking to the right, the correction angle is 0: correction_angle = 0
is looking up, the correction angle is 90: correction_angle = 90
is looking to the left, the correction angle is 180: correction_angle = 180
is looking down, the correction angle is 270: correction_angle = 270

Rotate the player with pygame.transform.rotate() by the angle around its center:
(See also How do I rotate an image around its center using Pygame?)



Minimal example: repl.it/@Rabbid76/PyGame-RotateWithMouse


回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap