我试图在Python中用命令模拟JS中可用的一些行为上下文.旋转(角度)。在
我有以下代码: 导入pygame 导入数学 将numpy作为np导入
pygame.init()
CLOCK = pygame.time.Clock()
RED = pygame.color.THECOLORS['red']
WHITE = pygame.color.THECOLORS['white']
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
screen_width, screen_height = screen.get_size()
surface = pygame.Surface((50, 50), pygame.SRCALPHA)
surface.fill((0, 0, 0))
rotated_surface = surface
rect = surface.get_rect()
ax = int(screen_width / 2)
ay = int(screen_height / 2)
angle = 0
print("Size of the screen ({}, {})".format(screen_width, screen_height))
print("Center of the screen ({}, {})".format(ax, ay))
myfont = pygame.font.SysFont("monospace", 12)
pygame.display.set_caption("Test rotate")
main_loop = True
amplifier = 200
def calculate_angle(mouse_position):
dx = mouse_position[0] - ax
dy = mouse_position[1] - ay
return np.arctan2(dy,dx)
while main_loop:
for event in pygame.event.get():
keys = pygame.key.get_pressed()
if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]:
main_loop = False
pos = pygame.mouse.get_pos()
angle = (calculate_angle(pos) * 180)/math.pi
screen.fill((255,255,255))
rotated_surface = pygame.transform.rotate(surface, -angle)
rect = rotated_surface.get_rect(center = (ax, ay))
screen.blit(rotated_surface, (rect.x, rect.y))
pygame.draw.line(rotated_surface, WHITE, (ax,ay), (ax+20, ay), 1)
pygame.draw.line(rotated_surface, WHITE, (ax+10,ay-10), (ax+20, ay), 1)
pygame.draw.line(rotated_surface, WHITE, (ax+10,ay+10), (ax+20, ay), 1)
pygame.display.update()
CLOCK.tick(30)
pygame.quit()
我画了一个箭头,想根据鼠标在屏幕上的位置旋转它。当然,每次做正弦、余弦计算时,我都可以重新画出线条,但这很痛苦。我认为曲面可以帮助我,事实上,它与完美旋转的矩形一起工作。但是把我的线条画到表面上是行不通的。在
所以,我想我误解了曲面的用途,或者我把代码写错了,还有更好的方法。请注意,如果我在绘制线说明,箭头确实在屏幕上绘制,但永远不会旋转。在
有什么想法(除了使用image/sprite;)?在
谢谢
问题是在曲面区域之外绘制箭头线。每个曲面的左上角坐标为(0,0),因此它们都有自己的(局部)坐标系。因为你用屏幕的中心坐标来画线,所以箭头不会在可见的表面区域绘制。在
我用局部坐标在while循环前面的原始曲面上画线,然后旋转它,在循环内部得到一个新的rect。在
我还试图改进一些东西(查看评论)。在
相关问题 更多 >
编程相关推荐