python - Pygame-同时旋转精灵并跟随路径
问题描述
我正在尝试制作一个被抛出的球的动画,并且我希望它同时旋转并遵循平滑的抛物线路径。但是,我似乎无法pygame.transform.rotate()
合作。
这是我到目前为止所尝试的:
import pygame
screen = pygame.display.set_mode((500, 500))
timer = pygame.time.Clock()
ball = pygame.sprite.Sprite()
ball.image = pygame.image.load("throwball.png")
ball.image = pygame.transform.scale(ball.image, (48,48))
ball.rect = ball.image.get_rect(topleft = (50,50))
ball.orig_image = ball.image
rotaterect = ball.rect
for i in range(60):
#pygame.draw.rect(screen, Color(255,255,255), ball.rect)
ball.image = pygame.transform.rotate(ball.orig_image, i*20)
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
screen.blit(ball.image, ball.rect)
pygame.display.update()
timer.tick(60)
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
while 1:
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
每当我运行代码时,球都会以不规则的方式移动。我做了第二个矩形,试图控制位置,但球最终形成了这样的路径:
显然每个框架上的定位都有问题,但我不确定为什么任何框架都会不合适,因为它们的位置是由它们的中心点决定的。
这是球的图像:
它是 16x16(正方形),所以我对为什么图像没有遵循干净的路径感到目瞪口呆。
解决方案
请注意,旋转图像的大小会有所不同。请参阅如何使用 Pygame 围绕其中心旋转图像?.
获取旋转图像的矩形,并将矩形的中心设置为辅助矩形的中心rotaterect
。这导致图像围绕中心对称对齐。
您错过了将 更新为ball.rect
旋转图像的实际大小:
ball.rect = ball.image.get_rect()
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
例子:
for i in range(60):
ball.image = pygame.transform.rotate(ball.orig_image, i*20)
ball.rect = ball.image.get_rect()
rotaterect.topleft = (5*i,((i-20)*(i-20) + 1)/5)
ball.rect.center = rotaterect.center
screen.blit(ball.image, ball.rect)
pygame.display.update()
推荐阅读
- r - 滚动连接不会在 data.table 中给出 NA 值
- cypress - 如何在赛普拉斯中使用灯具列表断言列表
- python-3.x - 如何将python列表中的不同字符串转换为bash脚本中的数组
- sql - LIKE 语句在 sql server 查询中不起作用
- grpc - gRPC 等待服务器就绪
- c# - 运行命令 dotnet --list-sdks 没有返回结果
- pyspark - 是否有任何方法可以在 AWS GLue 中连接/合并 DynamicFrame 对象?
- python - 在不包含任何额外空格或换行符的情况下遵循长字符串的行长指南?
- reactjs - 登录后无法重定向
- wordpress - Azure 应用程序网关上的 504 网关超时导致 WordPress 插件更新错误