unity相机跟踪
- 要想让相机跟踪,那么必须要进行初始的偏移量的设置,因为你的相机初始时就和物体保持了距离,那么只需要让之后的物体位置+初始的偏移位置,得到的就是相机的位置
看注释
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainCamera : MonoBehaviour
{
//要跟踪的物体
public Transform player1Transform;
//偏移量,类型是Vector3
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
//获得偏移量,因为本脚本加在camera上,不需要在获取camera gameobject
offset = transform.position - player1Transform.position;
}
// Update is called once per frame
void Update()
{
//设置即可
transform.position = offset + player1Transform.position;
}
}
让视野变大或者变小
不需要进行camera的y轴上的上升,camera不同模式下都有视野大小的选择项
如在透视矩阵中Projection
选项为perspective
,透视矩阵模式下,有Field of View
选项,可以控制视野的大小,Projection
为Orthographic
正交矩阵模式下,有size
选项可以控制视野范围,如下图所示
代码上也很好控制,这里以透视矩阵情况下举例,正交模式雷同
看注释
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainCamera : MonoBehaviour
{
public Transform player1Transform;
//相机
private Camera _mCamera;
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - player1Transform.position;
//得到相机
_mCamera = GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
transform.position = offset + player1Transform.position;
//进行视野的设置,让物体走动时,视野变大,2.1145只是自己随便设的变大倍数,也可以直接设置数值。
_mCamera.fieldOfView = player1Transform.position * 2.1145f;
}
}