SpriteKit Coordinates differ between iPad and iPho

2019-03-04 11:16发布

问题:

I have a very simple SpriteKit scene that is not behaving like I would expect. It is a universal app and the code that I am using to draw a single red square in the scene is as follows:

    let redSquare = SKSpriteNode(color: UIColor .redColor(), size: CGSizeMake(100.0, 100.0))
    redSquare.anchorPoint = CGPointMake(0.0, 0.0)
    redSquare.position = CGPointMake(1.0, 1.0)
    addChild(redSquare)

This code is in the GameScene didMoveToView method of the default app that xCode creates for you when you select SpriteKit game.

When run on the iPad it behaves as expected drawing the red square 1 point off the bottom and left edge of the screen.

When I run it on the iPHone 6 Plus simulator however it shows up like this:

The spaceship shows up at the correct touchpoint on both devices, however a println() of the touch location shows (1,1) on the iPad and (1,100) on the iPhone. This indicates that the coordinates from (x,0) - (x,99) are off the bottom of the iPhone screen which makes no sense to me at all.

Why do the two devices not display it the same way? The behavior is the same in both the simulators and on the actual devices.

Thanks! Scooter

回答1:

This is caused because the size of the screen on iPhone is incorrect - have a look in the scene's sks file, you should see the size of the scene is set to (1024, 768) by default. To correct this you need to set the scene size and scale mode:

scene.size = skView.bounds.size
scene.scaleMode = .AspectFill

You should do this is didMoveToView or when you instantiate the scene.