Unity3D學習筆記之一:相機緩動跟隨
阿新 • • 發佈:2019-01-26
開發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);
}
需要注意的幾點:
- 該指令碼需要新增到主攝像頭上
- 將角色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);
}
}
引數解析:
- 當前座標
- 目標點
- 移動速度
- 緩動引數,越小越快地接近目標
- 最大速度
- 上次呼叫該方程的時間