Reputation: 3541
I'm confused on how to rotate a line (SKShapeNode) around it's bottom point (begin point, here), think of a clock here.
I have the following, but it doesn't seem to be rotating as expected.
public let line = SKShapeNode()
private let linePath = CGMutablePath()
init(begin: CGPoint, end: CGPoint) {
self.begin = begin
self.end = end
linePath.move(to: begin)
linePath.addLine(to: end)
line.path = linePath
line.strokeColor = UIColor.black
line.lineWidth = 3
SceneCoordinator.shared.gameScene.addChild(line)
}
public func rotate(angle: Double) {
var transform = CGAffineTransform(rotationAngle: CGFloat(angle))
line.path = linePath.mutableCopy(using: &transform)
}
Upvotes: 0
Views: 409
Reputation: 540145
Your function rotates the path around the
shapes position
(which is (0, 0)
by default) and not around the starting point of the line as intended.
To solve the problem, create the shape with a position equal to the starting point of the line, and with a line relative to that point:
linePath.move(to: CGPoint.zero)
linePath.addLine(to: CGPoint(x: end.x - begin.x, y: end.y - begin.y))
line.path = linePath
line.position = begin
// ...
SceneCoordinator.shared.gameScene.addChild(line)
Note that instead of transforming the path you can rotate the node:
line.zRotation = angle
or with animation:
line.run(SKAction.rotate(toAngle: angle, duration: 0.2))
You can compute the position of the endpoint in the scene's coordinate system with
let endPos = line.convert(CGPoint(x: end.x - begin.x, y: end.y - begin.y), to: line.scene!)
Upvotes: 1