我最喜歡的一個(gè)字是吃,兩個(gè)字是旅行,三個(gè)字是你的名字.
晚上好, 接下來給大家分享攝像機(jī)的幾種跟隨方案.
方案1
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
//跟隨目標(biāo)
public Transform mFollower;
//相機(jī)的高度
public float offsetY;
//攝像機(jī)移動(dòng)處理一般放在LateUpdate
void LateUpdate ()
{
if (mFollower != null) {
Vector3 targetPoint = mFollower.position;
targetPoint.y += offsetY;
targetPoint.z -= 7f;
transform.position = Vector3.Lerp (transform.position, targetPoint, Time.deltaTime * 5f);
}
}
}
方案2
public class FollowPlayer : MonoBehaviour
{
//玩家
private Transform player;
public float speed = 4.0f;
void Start ()
{
player = GameObject.FindGameObjectWithTag (Tags.player).transform;
}
void Update ()
{
//攝像機(jī)跟隨
Vector3 targetPos = player.position + new Vector3 (0, 2.0f, -2.7f);
transform.position = Vector3.Slerp (transform.position, targetPos, speed * Time.deltaTime);
Quaternion targetRotation = Quaternion.LookRotation (player.position - transform.position);
transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);
}
}
方案3
public class CameraScript : MonoBehaviour
{
//攝像機(jī)跟離角色有多遠(yuǎn)
public float distanceAway;
//攝像機(jī)在角色上方多高
public float distanceUp;
//攝像機(jī)移動(dòng)的速度
public float smooth;
//目標(biāo)位置
private Vector3 targetPosition;
//攝像機(jī)所跟隨的對象的位置,此處是角色物體的位置
Transform follow;
// Use this for initialization
void Start ()
{
//得到要跟隨的物體對象的位置
follow = GameObject.FindGameObjectWithTag ("Player").transform;
}
// Update is called once per frame
void Update ()
{
//得到攝像機(jī)要移動(dòng)的目標(biāo)位置
targetPosition = follow.position + Vector3.up * distanceUp -follow.forward * distanceAway;
//攝像機(jī)從當(dāng)前位置移動(dòng)到目標(biāo)位置
transform.position = Vector3.Lerp (transform.position, targetPosition, Time.deltaTime * smooth);
//攝像機(jī)要看向角色物體
transform.LookAt (follow);
}
}
方案4
攝像機(jī)隨鼠標(biāo)旋轉(zhuǎn)并且限制角度
public class CubeScript : MonoBehaviour
{
float ver;
// 限制角度
float fv = 20;
Quaternion last;
void Update ()
{
ver = Input.GetAxis ("Mouse Y");
float angle = Vector3.Angle (Vector3.up, transform.forward);
if (angle > 90 + fv || angle < 90 - fv) {
transform.rotation = last;
} else {
last = transform.rotation;
Vector3 tmp = new Vector3 (transform.eulerAngles.x - ver * Time.deltaTime * 60f,
transform.eulerAngles.y,
transform.eulerAngles.z);
transform.eulerAngles = tmp;
}
}
}
代碼比較簡單不在解釋, 如有疑問請留言.
另外再分享一個(gè)
[仿魔獸世界視角的Demo](https://pan.baidu.com/s/1jI2YI14)
密碼: jt9s