earlygrey / shapedrawer

A library for libGDX that draws simple shapes using a batch.
MIT License
185 stars 32 forks source link

ring segment #51

Open judos opened 3 years ago

judos commented 3 years ago

Would it be possible to add ring segments to Shapedrawer?

135876399-4044b5eb-64b5-4b75-a721-f8c0bf998d32

I have just created a custom function for myself to draw this. Maybe someone else also finds it helpful if it is in ShapeDrawer.

fun ringSegmentPolygon(): Pair<FloatArray, ShortArray> {
  if (polygon != null) return polygon!!
  val deltaAngle = (ang2.radian + MathUtils.PI2 - ang1.radian) % MathUtils.PI2 //ang2 might be smaller than ang1, see below explanation
  val sides = max(3, ceil(deltaAngle / MathUtils.HALF_PI * 12))
  val dAnglePerSide = deltaAngle / sides
  // 2 points, 2 numbers (x,y) per segment
  val vertex = FloatArray((sides + 1) * 2 * 2)
  val triang = ShortArray(sides * 2 * 3)
  var angle = ang1.radian
  for (i in 0..sides) {
    val cos = cos(angle)
    val sin = sin(angle)
    angle += dAnglePerSide
    vertex[i * 4 + 0] = center.x + cos * rIn
    vertex[i * 4 + 1] = center.y + sin * rIn
    vertex[i * 4 + 2] = center.x + cos * rOut
    vertex[i * 4 + 3] = center.y + sin * rOut
    if (i < sides) {
      triang[i * 6 + 0] = (i * 2 + 0).toShort()
      triang[i * 6 + 1] = (i * 2 + 1).toShort()
      triang[i * 6 + 2] = (i * 2 + 2).toShort()
      triang[i * 6 + 3] = (i * 2 + 1).toShort()
      triang[i * 6 + 4] = (i * 2 + 2).toShort()
      triang[i * 6 + 5] = (i * 2 + 3).toShort()
    }
  }
  polygon = Pair(vertex, triang)
  return polygon!!
}

Explanation of the variables: ang1.radian: starting angle in radian in range [ 0, 2PI ] ang2.radian: end angle in radian in range [ 0, 2PI ], Note: if the segment spans from e.g. 350° (start) to 10° (end) then the end angle (10° = 0.17 radian) is smaller than starting angle (350° = 6.10 radian) center: Point with x,y floats (center of the full circle) rIn: radius of the inner circle rOut: radius of the outer circle

Code is in Kotlin, let me know if you want to add it and if you need any help with the code!

Cheers, judos