Resize the Player Node on Device Rotation
Apple Game Frameworks and Technologies — by Tammy Coron (91 / 193)
👈 Add Support for All Devices a nd Orientations | TOC | Lock the Location of the On-Screen Controls 👉
In Setting the Camera’s Viewport, you learned about the camera’s viewport and how certain camera settings, like its position and scale, have an inverse effect on how the scene renders. Armed with that information, you can solve the problem of the resizing player.
Still inside the GameScene.swift file, add the following code to the didChangeLayout() method:
let w = view?.bounds.size.width ?? 1024
let h = view?.bounds.size.height ?? 1336
if h >= w { // portrait, which matches the design
camera?.setScale(1.0)
} else {
camera?.setScale(1.25) // helps to keep relative size
// larger numbers results in "smaller" scenes
}
This code first checks the height and width of the view using default values if needed; it then adjusts the scale of the camera to shrink the size of the nodes within its view.
You could argue that it makes equal sense to adjust only the player sprite, but then what happens when you start adding more game objects? You’d have to loop through each object and resize it. Why go through all of that when you can accomplish the same thing by setting the camera’s scale?