libgdx drawing arc curve

后端 未结 4 1697
南旧
南旧 2020-12-19 23:01

The arc function of libgdx instead of drawing a arc draws a pie segment (ie. has 2 lines connecting to the arc\'s origin)

shapeRenderer.begin(ShapeType.Line)         


        
4条回答
  •  被撕碎了的回忆
    2020-12-19 23:32

    Here's a simple solution that uses kotlin extensions.

    /** Draws an arc with 'stroke' of given width  */
    fun ShapeRenderer.strokeArc(strokeWidth: Float, x: Float, y: Float, radius: Float, start: Float, degrees: Float, sampling: Float = 2f, color: Color = Color.WHITE) {
        val segments = ((6 * Math.cbrt(radius.toDouble()) * (Math.abs(degrees) / 360.0f)) * sampling).toInt()
        val colorBits = color.toFloatBits()
    
        for (i in 0 until segments) {
            val x1 = radius * MathUtils.cosDeg(start + (degrees / segments) * i)
            val y1 = radius * MathUtils.sinDeg(start + (degrees / segments) * i)
    
            val x2 = (radius - strokeWidth) * MathUtils.cosDeg(start + (degrees / segments) * i)
            val y2 = (radius - strokeWidth) * MathUtils.sinDeg(start + (degrees / segments) * i)
    
            val x3 = radius * MathUtils.cosDeg(start + (degrees / segments) * (i + 1))
            val y3 = radius * MathUtils.sinDeg(start + (degrees / segments) * (i + 1))
    
            val x4 = (radius - strokeWidth) * MathUtils.cosDeg(start + (degrees / segments) * (i + 1))
            val y4 = (radius - strokeWidth) * MathUtils.sinDeg(start + (degrees / segments) * (i + 1))
    
            renderer.color(colorBits)
            renderer.vertex(x + x1, y + y1, 0f)
            renderer.color(colorBits)
            renderer.vertex(x + x3, y + y3, 0f)
            renderer.color(colorBits)
            renderer.vertex(x + x2, y + y2, 0f)
    
            renderer.color(colorBits)
            renderer.vertex(x + x3, y + y3, 0f)
            renderer.color(colorBits)
            renderer.vertex(x + x2, y + y2, 0f)
            renderer.color(colorBits)
            renderer.vertex(x + x4, y + y4, 0f)
        }
    }
    

    To make better sense of this and why the built in solution does what it does. ShapeRenderer draws in triangles (just as OpenGL does) So you need 3 vertexes to draw a triangle. Here we are drawing one segment at a time. Each segment is 2 triangles to make a rectangle. Enough rectangles starts to look like a smooth circle.

    The way the built in ShapeRenderer.arc draws is much like a pie. If you have enough slices with straight edges it starts to look like a full pie rather than a bunch of triangles to the center.

    I hope this makes some sense and allows others to draw their own custom shapes and learn for the future!

提交回复
热议问题