问题
I have a SKSpriteNode that is too big for the view and I am looking for a simple way in Sprite Kit to scroll horizontally to be able to see it completely.
Thanks!

回答1:
You could try using an SKCameraNode
and respond to a pan gesture like so:
// GameScene.swift
override func didMove(to view: SKView) {
self.camera = SKCameraNode()
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePanFrom(recognizer:)))
panGestureRecognizer.maximumNumberOfTouches = 1
view.addGestureRecognizer(panGestureRecognizer)
}
func handlePanFrom(recognizer: UIPanGestureRecognizer) {
if recognizer.state != .changed {
return
}
// Get touch delta
let translation = recognizer.translation(in: recognizer.view!)
// Move camera
self.camera?.position.x -= translation.x
self.camera?.position.y += translation.y
// Reset
recognizer.setTranslation(CGPoint.zero, in: recognizer.view)
}
回答2:
The easiest way to get neat scroll-view-like UX is ... to use a Scroll View. Nest one in your SKSceneView:
Scene View
|-Scroll View
Then you need to set up a contentSize
of the Scroll View according to the scene width and viewport width. Here you should make some corresponding calculations depending on the scaleMode
of the scene and other specific features of your layout.
There are very good lessons from Raywenderlich on this topic:
Scroll View School Part 13: Sprite Kit Integration
Scroll View School Part 14: Sprite Kit Level Selector
The lessons are good because they are very detailed. They will tell you how to convert coordinates correctly. However, some things are not ideal there: for example you don't need to add a content view to the scroll view, setting the contentSize
will be enough. Also, I recommend to use SKCameraNode
instead of putting everything in a root "world" node.
After this you must listen to the Scroll View's delegate
:
// Example from one of my games
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollWidth = scrollView.contentSize.width - scrollView.bounds.width
guard scrollWidth > 0.01 else { return }
let relativePosX = scrollView.contentOffset.x / scrollWidth
// Feed relative position to the scene.
// `setCameraRelativePosition` will convert it into the absolute camera
// coordinates in the scene coordinate space
gameScene.setCameraRelativePosition(relativePosX)
}
... and update your tilemap or camera position as appropriate.
UIPanGestureRecognizer
will never give your deceleration and bouncing like a native Scroll View.
来源:https://stackoverflow.com/questions/40062698/ios-how-to-scroll-horizontally-in-sprite-kit