官术网_书友最值得收藏!

Improving the camera

Our camera code works well; it follows the player wherever they fly. However, we can improve the camera to enhance the flying experience. In this section, we will add two new features:

  • Zoom the camera out as Pierre Penguin flies higher, reinforcing the feeling of increasing height.
  • Suspend vertical centering when the player drops below the halfway point of the screen. This means the ground never fills too much of the screen and adds the feeling of cutting upwards into the air when Pierre flies higher and the camera starts tracking him again.

Follow these steps to implement these two improvements:

  1. In GameScene.swift, create a new variable in the GameScene class to store the center point of the screen:
          var screenCenterY:CGFloat = 0 
  2. In the didMove function, set this new variable with the calculated center of the screen's height:
            // Store the vertical center of the screen: 
    screenCenterY = self.size.height / 2 
  3. We need to rework the didSimulatePhysics function significantly. Remove the existing didSimulatePhysics function and replace it with this code:
            override func didSimulatePhysics() { 
                // Keep the camera locked at mid screen by default: 
    var cameraYPos = screenCenterY
    cam.yScale = 1 
    cam.xScale = 1 
    
                // Follow the player up if higher than half the screen: 
                if (player.position.y>screenCenterY) { 
    cameraYPos = player.position.y
                    // Scale out the camera as they go higher: 
                    let percentOfMaxHeight = (player.position.y - 
    screenCenterY) / (player.maxHeight - 
    screenCenterY) 
                    let newScale = 1 + percentOfMaxHeight
    cam.yScale = newScale
    cam.xScale = newScale
                } 
    
                // Move the camera for our adjustment: 
    self.camera!.position = CGPoint(x: player.position.x, 
                    y: cameraYPos) 
            } 

Run the project and then fly up. The world scales smaller as you gain height. The camera also now allows Pierre to dive below the center of the screen when you fly close to the ground. The following screenshot illustrates the two extremes.

Notice the smaller sprites here; Pierre flies higher and the camera zooms out:

Improving the camera

In this screenshot, the camera stops following Pierre vertically as he approaches the ground:

Improving the camera

The combined effect adds a lot of polish to the game and increases the fun of flying. Our flying mechanic feels great. The next step is to move Pierre forward through the world.

主站蜘蛛池模板: 霍城县| 曲阳县| 肥西县| 佳木斯市| 保靖县| 宜黄县| 商河县| 社会| 凌源市| 大悟县| 炉霍县| 大宁县| 剑河县| 繁峙县| 东乡族自治县| 香格里拉县| 福鼎市| 梓潼县| 肃宁县| 乐山市| 景东| 花莲县| 万山特区| 建水县| 新巴尔虎左旗| 锡林浩特市| 柳州市| 龙岩市| 略阳县| 鸡东县| 锦州市| 开化县| 乐都县| 冀州市| 徐州市| 丹阳市| 北海市| 夏邑县| 利津县| 丰顺县| 汉沽区|