简体   繁体   English

两点之间的角度在 Pygame 中不起作用

[英]Angle between two points isn't working in Pygame

Everywhere online says to use atan2(pointA.y-pointB.y, pointA.x, pointB.x) but it just doesn't work.网上到处都说要使用 atan2(pointA.y-pointB.y, pointA.x, pointB.x) 但它不起作用。

import pygame
import sys
from math import *

WIDTH, HEIGHT = 1024, 576
screen = pygame.display.set_mode((WIDTH, HEIGHT))

def rot(surface, angle):
    rotated_surface = pygame.transform.rotozoom(surface, angle, 1)
    rotated_rect = rotated_surface.get_rect()
    return rotated_surface, rotated_rect

surf = pygame.Surface((64, 32), flags=pygame.SRCALPHA)
surf.fill((255, 0, 0))

def map_range(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin

    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)

    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    mouse_pos = pygame.Vector2(pygame.mouse.get_pos())

    center = pygame.Vector2(surf.get_rect().center)
    
    angle = degrees(atan2(mouse_pos.y - center.y, mouse_pos.x - center.x))

    rotated_surface = rot(surf, angle)
    rotated_surface[1].center = (WIDTH/3, HEIGHT/3)

    screen.fill((0,0,0))

    screen.blit(rotated_surface[0], rotated_surface[1])

    pygame.display.update()

I converted it in degrees and all, but it just doesn't rotate properly towards the cursor.我将它转换为度数,但它只是没有正确地向 cursor 旋转。 Am I missing something?我错过了什么吗?

  1. You're using the center of surf in your calculation.您在计算中使用 surf 的中心。 The center of surf is in the top-left of your screen.冲浪的中心位于屏幕的左上角。 Use the center of your rotated_surface.使用您的旋转表面的中心。
  2. Negate the angle.否定角度。

2 Mistakes: 2个错误:

  1. The center of the object is ( WIDTH/3 , HEIGHT/3 ) object 的center是 ( WIDTH/3 , HEIGHT/3 )
  2. The y-axis of the pygame coordinate system points down. pygame 坐标系的 y 轴指向下方。 So you need to invert the y-axis before calculating the angle.因此,您需要在计算角度之前反转 y 轴。
center = pygame.Vector2(WIDTH/3, HEIGHT/3)
angle = degrees(atan2(-(mouse_pos.y - center.y), mouse_pos.x - center.x))
rotated_surface = rot(surf, angle)
rotated_surface[1].center = center.x, center.y

See also How to know the angle between two vectors?另请参阅如何知道两个向量之间的角度? and How to rotate an image(player) to the mouse direction?以及如何将图像(播放器)旋转到鼠标方向? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM