1. 程式人生 > >Unity3D學習筆記之一:相機緩動跟隨

Unity3D學習筆記之一:相機緩動跟隨

開發2D遊戲時常會遇到角色在區域內移動時,需要相機跟隨以便始終保持角色居中,效果如下:

這裡寫圖片描述

在這裡需要遇到的是Unity內建的Mathf物件的SmoothDamp()緩動函式
方法如下:

  void Update () {
        float newPosY = Mathf.SmoothDamp(transform.position.y, target.transform.position.y,
            ref yVelocity, smoothTime);
        float newPosX = Mathf.SmoothDamp(transform.position
.x, target.transform.position.x, ref xVelocity, smoothTime); transform.position = new Vector3(newPosX, newPosY, transform.position.z); }

需要注意的幾點:

  1. 該指令碼需要新增到主攝像頭上
  2. 將角色GameObject繫結到該指令碼上,作為target

完整程式碼如下:

using UnityEngine;
using System.Collections;

public class CameraFixed : MonoBehaviour {

    public
GameObject target; public float smoothTime = 0.3f; public float yVelocity = 0.0f; public float xVelocity = 0.0f; // Use this for initialization void Start () { } void Update () { float newPosY = Mathf.SmoothDamp(transform.position.y, target.transform.position.y, ref
yVelocity, smoothTime); float newPosX = Mathf.SmoothDamp(transform.position.x, target.transform.position.x, ref xVelocity, smoothTime); transform.position = new Vector3(newPosX, newPosY, transform.position.z); } }

引數解析:
這裡寫圖片描述

  1. 當前座標
  2. 目標點
  3. 移動速度
  4. 緩動引數,越小越快地接近目標
  5. 最大速度
  6. 上次呼叫該方程的時間