How to draw a n sided regular polygon in cartesian coordinates?

前端 未结 6 1950
北荒
北荒 2020-12-04 17:09

I have been trying to figure out how to write a simple program to compute the x,y points for creating a regular polygon of n sides. Can someone give me some code examples th

6条回答
  •  佛祖请我去吃肉
    2020-12-04 17:23

    The "for n_sides:" answer is the easiest. For the guy who suggested that you could simplify the calculations by using complex numbers, nearly all math libraries have table-based cos() and sin() routines with efficient interpolation so there's no need to delve into relatively obscure solutions. Usually a regular n-gon can be initialized and the hardware scaling of OpenGL used to scale / transform it for any particular instance.

    If you want to be hardcore about it, pre-generate all the n-gons you need and load them into vertex buffers.

    As an aside, here's the above solution in Lua. It just prints out the coordinates, but you're of course free to return the coordinates in an array / table. The coordinates returned can be used to initialize an OpenGL GL_LINE_LOOP mesh primitive.

    require 'math'
    
    -- computes coordinates for n-sided, regular polygon of given radius and start angle
    -- all values are in radians
    
    function polypoints(sides, radius, start)
        local x_center = 0.0
        local y_center = 0.0
        local angle = start
        local angle_increment = 2 * math.pi / sides
        local x=0.0
        local y=0.0
    
        print(string.format("coordinates for a %d sided regular polygon of radius %d\nVertex",sides,radius),"X"," ","Y")
        for i=1,sides do
            x = x_center + radius * math.cos(angle)
            y = y_center + radius * math.sin(angle)
            print(string.format("%d\t%f\t%f",i,x,y))
            angle = angle + angle_increment
        end
    end
    
    -- Generate a regular hexagon inscribed in unit circle 
    polypoints(6, 1.0, 0.0)
    

提交回复
热议问题