Basic trigonometry isn't working correctly in python

落爺英雄遲暮 提交于 2019-12-25 05:48:06

问题


For a bit of background, this is the game I'm trying to draw in an isometric style.

I'm just trying to get the correct calculations instead of doing it in a hacky way, but one part isn't working, and I'm not quite sure about the other part (I'll save that for another question later on).

So, forgetting the little squares inbetween, the board is made up of n lenels. I'd like to be able to calculate the coordinates for these so I can do further calculations on them, but the trig isn't working, and to the best of my knowledge (bear in mind I last did it years ago), it should be.

This is the simple code to draw the first square:

import turtle
import math

iso_angle = 20
grid_length = 100

turtle.right(iso_angle)
turtle.forward(grid_length)
turtle.right(180 - iso_angle * 2)
turtle.forward(grid_length)
turtle.right(iso_angle * 2)
turtle.forward(grid_length)
turtle.right(180 - iso_angle * 2)
turtle.forward(grid_length)

Using sohcahtoa, I thought I'd be able to calculate the width and height of the resulting square, since it's effectively made up of 4 triangles, and I can double the height of one of the triangles.

#s = o / h
#sin(iso_angle) = o / grid_length
#o = sin(iso_angle) * grid_length

height = 2 * sin(iso_angle) * grid_length
width = 2 * cos(iso_angle) * grid_length

However, when I move the turtle down by height, it doesn't fall on the edge of the square. It doesn't even move in a multiple of the distance of the edge, it just seems to end up some random distance. Swapping with width doesn't work either.

Where abouts am I going wrong with this?


回答1:


As stated in the comments you need to convert to radians which can be done with the

math.radians()

function. So in practice you would end with something like

height = 2 * sin(math.radians(iso_angle)) * grid_length
width = 2 * cos(math.radians(iso_angle)) * grid_length



回答2:


The cursor module (turtle) takes angles in degrees.

The sin() and cos() math functions take angles in radians. You must convert them. Fortunetly, Python includes convenient functions to do that in the math module:

height = 2 * sin(radians(iso_angle)) * grid_length

Hope this helps.



来源:https://stackoverflow.com/questions/32980003/basic-trigonometry-isnt-working-correctly-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!