Reputation: 3241
I have a UIView
that I want to position on top of a certain area in an SKScene
.
This is the point that I have in my SKScene
:
guard let point = elementCGPoints.centroid() else {
return
}
And I'm trying to use this SKView
method to convert from scene coordinates to view coordinates; based on this SO discussion:
let convertedPoint = canvasScene.convertPoint(toView: point)
selectionBox.frame = CGRect(x: convertedPoint.x, y: convertedPoint.y, width: 100, height: 100)
However, this ends up always displaying at a point far beyond the range of my view.
Any intuition about how to do this right?
Upvotes: 0
Views: 182
Reputation: 1339
here are two ways. the first is responding to UITouch inside SKScene
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let locationInWindow = touch.location(in: touch.window)
let locationInView = touch.location(in: self)
gameSceneDelegate?.moveView(toPosition: locationInWindow) //move a UIView to window position (via delegate pattern)
shape.position = locationInView //move a SKNode to same position in scene
}
this is easiest. but your question suggests you want to use convertPoint
in which case you could convert an arbitrary point from scene to view like this
//inside SKScene
let random_point = CGPoint(x: CGFloat.random(in: 0...100), y: CGFloat.random(in: 0...100))
let converted_point = self.convertPoint(toView: random_point)
gameSceneDelegate?.moveView(toPosition: converted_point) //move a UIView to window position (via delegate pattern)
shape.position = random_point //move a SKNode to same position in scene
and the UIViewController delegate would look like this
protocol GameSceneDelegate : UIViewController {
func moveView(toPosition position:CGPoint)
}
class GameViewController: UIViewController, GameSceneDelegate {
[...]
func moveView(toPosition p:CGPoint) {
myView?.frame.origin = p
}
}
Upvotes: 1