In a triangulated isometric grid, what triangle is a given point in?

前端 未结 2 2049
半阙折子戏
半阙折子戏 2021-01-12 15:55

I have a triangulated isometric grid, like this:
(source: mathforum.org)

In my code, triangles are grouped by columns.

As I hover the mouse

2条回答
  •  走了就别回头了
    2021-01-12 16:04

    This is similar to what cletus said, but a different way to look at it I suppose.

    I am assuming the triangle side is 1.

    Suppose you have the grid as below:

           y'
          /
         /__/__/__/__/__/__/
        /__/__/__/__/__/__/
       /__/__/__/__/__/__/____ x'
    (0,0)
    

    If you consider the grid in a co-ordinate system in which the x & y axes are at an angle of 60 degrees, a point whose co-ordinate in the angled system (x',y') will correspond to the coordinate in the orthogonal system (with same origin an general direction of axes) to (x,y).

    In your problem, you are given (x,y), we need to find (x',y') and then figure out the triangle.

    If i is the unit vector along x and j the orthogonal along y, then we have that

    x'* i + y'( i/2 + sqrt(3) * j /2) = xi + yj.
    

    (Basically the unit vector along the 'angled' y axis is i/2 + sqrt(3)/2 * j. The unit vector along the x axis is the same as the normal x-axis, i.e. i).

    Thus

    x' + y'/2 = x
    y' * sqrt(3)/2 = y
    

    Solving gives:

    y' = 2*y/sqrt(3)
    x' = x - y/sqrt(3)
    

    Assume for now that x' and y' are positive.

    Now if c = [x'], the integer part of x'

    and r = [y'], the integer part of y'

    then in the (angular) grid, the point lies in the cth column and the rth row. (Counting right and up and start counting at 0).

    Thus we have narrowed down your point to a parallelogram

           ____
          /\ * /   
         /___\/
       (c,r)
    

    Now in order to find out which triangle it is in you can consider the fractional parts of x' and y'.

    {x} = x' - [x'] = x' - c.
    {y} = y' - [y'] = y' - r.
    

    Now,

    if {x} + {y} > 1, then the point lies in the triangle marked with *. if {x} + {y} < 1, then the point lies in the other triangle. if {x} + {y} = 1, then the point lies on the line common to the two triangles.

    Hope that helps too.

提交回复
热议问题