Resize the Player Node on Device Rotation

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?

Build and run the project. Rotate the device and notice how much closer in size that the player sprite is when it is in landscape orientation than it was previously:

images/OperatingTheCameraAndUsingReferenceNodes/scene-editor-smaller-player.png

Now that you have the player sprite respecting its size on rotation, you’re ready to tackle the final problem: disappearing controls.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset