簡體   English   中英

兩點之間的角度在 Pygame 中不起作用

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

網上到處都說要使用 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()

我將它轉換為度數,但它只是沒有正確地向 cursor 旋轉。 我錯過了什么嗎?

  1. 您在計算中使用 surf 的中心。 沖浪的中心位於屏幕的左上角。 使用您的旋轉表面的中心。
  2. 否定角度。

2個錯誤:

  1. object 的center是 ( WIDTH/3 , HEIGHT/3 )
  2. pygame 坐標系的 y 軸指向下方。 因此,您需要在計算角度之前反轉 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

另請參閱如何知道兩個向量之間的角度? 以及如何將圖像(播放器)旋轉到鼠標方向? .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM