I'm using Swift/SpriteKit and created a wide image of a map on a SKScene. I'm doing this all in code and wanted to let the user drag their finger to pan across this extra wide map. Think of it like an old school RPG map of a fantasy land. I was able to achieve the panning, but the image is initially in the center of the screen (meaning the user can pan left or right).
The thing is, I wanted them to "start" all the way left, so they can only initially pan right to see the other side of the map (they can only pan horizontally).
Is there a way to start the initial position on a wide image in this manner?
override func didMoveToView(view: SKView) {
self.scaleMode = SKSceneScaleMode.Fill;
background = SKSpriteNode(imageNamed: "map")
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
background.blendMode = .Replace
background.zPosition = -1
addChild(background)
let pan = UIPanGestureRecognizer(target: self, action: "dragScene:")
pan.minimumNumberOfTouches = 1;
self.view!.addGestureRecognizer(pan)
}
func dragScene(gesture: UIPanGestureRecognizer)
{
let xRange = SKRange(lowerLimit: 250,upperLimit: 764)
let yRange = SKRange(lowerLimit:0,upperLimit:size.height)
background.constraints = [SKConstraint.positionX(xRange,y:yRange)]
let trans = gesture.translationInView(self.view)
let moveMap = SKAction.moveBy(CGVector(dx: trans.x * 0.08, dy: 0), duration: 0.0)
background.runAction(moveMap)
}
I tried changing the position of the map below like this
CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
to
CGPointMake(CGRectGetMinX(self.frame), CGRectGetMidY(self.frame));
(so using min instead of middle) but that just created a lot of grey space on the left (after panning it snapped into place fine, but I didn't want to make the user have to do that).
Any ideas?
Thanks!
Well, maybe this isn't the best way, but here is how I solved it:
let xRange = SKRange(lowerLimit: 250,upperLimit: 764)
let yRange = SKRange(lowerLimit:0,upperLimit:size.height)
background.constraints = [SKConstraint.positionX(xRange,y:yRange)]
background.runAction(SKAction.moveBy(CGVector(dx: 2000, dy: 0), duration: 0.0))
I added this code in the didMoveToView, just after I add the background node to the screen for the first time.
..So the idea is, just set constraints and then move your image absurdly far to the left and the constraints will prevent it from going too far.
..Then the user can pan normally. This worked!