所以我正在學習 python 教程,我需要通過給定的斜邊 = 40 和角度 = 45 度來找到 x 和 y。誰能解釋如何找到x和y?

這是python中的代碼。查看 movePlayer 函式。尋找新的 x 和 y 的方式不同。該角度首先從 180 中減去,然后除以 2,這沒有意義但它有效。
import pygame, math
pygame.init()
def movePlayer(direction, radius, absRot):
yChange = 5
# how many degrees to move in either side
deltaTheta = int(90/(radius / yChange))
if direction == 'left':
deltaTheta *= -1
# convert degrees to radians
finalRot = (absRot deltaTheta) * math.pi / 180
hypotenuse = (radius * math.sin(finalRot) / (math.sin((math.pi - finalRot) / 2)))
# why these work
newX = hypotenuse * math.cos(math.pi/2-(math.pi - finalRot)/2)
newY = hypotenuse * math.sin(math.pi/2-(math.pi - finalRot)/2)
# these don't work
#newX = hypotenuse * math.cos(math.pi/2-finalRot)
#newY = hypotenuse * math.sin(math.pi/2-finalRot)
return newX, newY,absRot deltaTheta
WIDTH = 900
HEIGHT = 700
SCREEN_SIZE = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(SCREEN_SIZE)
player = pygame.Surface((64,64))
playerStart = player
currentRotation = 0
ball = pygame.Surface((32,32))
ball.fill('red')
playerX = WIDTH // 2
playerY = 530
playerXOriginal = playerX
playerYOriginal = playerY
ballX = WIDTH // 2 - ball.get_rect().width // 2
ballY = 450 - ball.get_rect().height // 2
radius = playerY - ballY
FPS = 30
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
pressedKeys = pygame.key.get_pressed()
if pressedKeys[pygame.K_LEFT]:
changeX, changeY, currentRotation = movePlayer('left', radius, currentRotation)
playerX = playerXOriginal changeX
playerY = playerYOriginal - changeY
print('left')
elif pressedKeys[pygame.K_RIGHT]:
changeX, changeY, currentRotation = movePlayer('right', radius, currentRotation)
playerX = playerXOriginal changeX
playerY = playerYOriginal - changeY
print('right')
screen.fill('white')
screen.blit(ball, (ballX,ballY))
screen.blit(player, (playerX - player.get_rect().width //2,playerY - player.get_rect().height // 2))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
uj5u.com熱心網友回復:
有點基本的三角學(假設 ang 是弧度,零角度指向 x)。
x = cos(ang) * h
y = sin(ang) * h
uj5u.com熱心網友回復:
在您的情況下,您的角度為 45 度,因此您有一個直角等腰三角形。
一般的畢達哥拉斯公式是:h^2 = x^2 y^2.
由于三角形是等腰三角形,則:
x = y => h^2 = 2 * x^2 => x = y = (sqrt(2)/2)*h
在更一般的情況下,三角形不是等腰三角形:
x = cos(ang) * h
y = sin(ang) * h
在蟒蛇中:
import math
def triangleSides(hypotenuse,angleindegrees):
angleinradians = (angleindegrees * math.pi / 180)
(x,y) = hypotenuse* math.cos(angleinradians),hypotenuse* math.sin(angleinradians)
return (x,y)
uj5u.com熱心網友回復:
為了得到 x,y 坐標,從 (x,y) 畫一條直線與 x 軸成直角是很方便的。鑒于圖表,我將做出以下兩個假設:
- 左下角是 90 度(這意味著它是一個等腰直角三角形)
- 三角形的右下角位于原點(圖中的藍點)。
使用勾股定理,我們得到 x = - (40 / sqrt(2)) 和 y = 40 / sqrt(2)。
要使用三角函式,我們得到:
a, h = math.pi/4, 40
x, y = - h * cos(a), h * sin(a)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362854.html
上一篇:APL中的因子數字總和(ProjectEuler20)
下一篇:以演算法方式執行浮點加法
