Skip to content

Instantly share code, notes, and snippets.

@uchcode
Last active July 5, 2020 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uchcode/a91f06a8c9cd9b8c14416fd264a34154 to your computer and use it in GitHub Desktop.
Save uchcode/a91f06a8c9cd9b8c14416fd264a34154 to your computer and use it in GitHub Desktop.
Regular Polygon Shape in SpriteKit
import SpriteKit
func CGPolygonPath(radius: CGFloat, vertices: CGFloat) -> CGPath {
let path = CGMutablePath()
let angle = 360.0 / vertices
var i = CGFloat(1.0); while i <= vertices {
let degrees = angle * i + 90.0
let radians = degrees * .pi / 180.0
let point = CGPoint(
x: cos(radians) * radius,
y: sin(radians) * radius
)
if i == 1.0 {
path.move(to: point)
} else {
path.addLine(to: point)
}
i += 1.0
}
path.closeSubpath()
return path
}
extension SKShapeNode {
public convenience init(polygonOfRadius r: CGFloat, vertices v: Int) {
self.init(path: CGPolygonPath(radius: r, vertices: CGFloat(v)))
}
public convenience init(triangleOfRadius r: CGFloat) {
self.init(path: CGPolygonPath(radius: r, vertices: 3.0))
}
}
SKShapeNode(polygonOfRadius: 50, vertices: 0)
SKShapeNode(polygonOfRadius: 50, vertices: 1)
SKShapeNode(polygonOfRadius: 50, vertices: 2)
SKShapeNode(polygonOfRadius: 50, vertices: 3)
SKShapeNode(polygonOfRadius: 50, vertices: 4)
SKShapeNode(polygonOfRadius: 50, vertices: 5)
SKShapeNode(triangleOfRadius: 50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment