如何让PYGAME中的图像在旋转时保持静止? [英] How to make an image in pygame stay still when rotated?

查看:26
本文介绍了如何让PYGAME中的图像在旋转时保持静止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在尝试让图像指向鼠标,这在某种程度上是有效的。图像指向鼠标,但它在四处移动。我不知道这是不是形象上的问题,但如果有任何帮助,我们将不胜感激。如果您不知道,方向是通过获取鼠标位置和图像位置之间的差值,通过atan函数运行它,除以6.28,然后乘以360来计算的。这将导致鼠标偏离图像的程度。代码是这样的。另外,我应该归功于图像的开发者,所以在这里。由mynamepongwww.flaticon.com

制作的图标
import pygame
import math
pygame.init()
win_height=800
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("Rotation Test")

black=(0,0,0)

carx=200
cary=200

clock=pygame.time.Clock()
car=pygame.image.load("inkscape images for games/car.png")
car=pygame.transform.scale(car,(100,100))

while True:
    mouse=pygame.mouse.get_pos()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
    angle=math.atan2(mouse[0]-carx,mouse[1]-cary)/6.28*360
    win.fill(black)
    car_rotated=pygame.transform.rotate(car,angle)
    win.blit(car_rotated,(carx,cary))
    pygame.display.update()

推荐答案

您需要设置汽车中心,然后围绕该点旋转汽车。

尝试此代码:

import pygame
import math
pygame.init()
win_height=800
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("Rotation Test")

black=(0,0,0)

# center of car rect
carx=400
cary=400

clock=pygame.time.Clock()
car=pygame.image.load("inkscape images for games/car.png")
car=pygame.transform.scale(car,(100,100))

while True:
    mouse=pygame.mouse.get_pos()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()

    angle=math.atan2(mouse[0]-carx,mouse[1]-cary)/6.28*360-90
    win.fill(black)
    car_rotated=pygame.transform.rotate(car,angle)
    new_rect = car_rotated.get_rect(center = (carx, cary))
    win.blit(car_rotated,(new_rect.x,new_rect.y))
    pygame.display.update()

输出

这篇关于如何让PYGAME中的图像在旋转时保持静止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆