Basic trigonometry isn't working correctly in

2019-09-04 13:07发布

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?

2条回答
老娘就宠你
2楼-- · 2019-09-04 13:55

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.

查看更多
Deceive 欺骗
3楼-- · 2019-09-04 14:01

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
查看更多
登录 后发表回答