在Unity项目中,有时候需要呈现一直跟随摄像头移动的,能够全屏的一个quad长方形,quad加载纹理,就可以一直显示全屏了。
把这个脚本绑定到Camera上,具体代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera : MonoBehaviour
{
private GameObject _textureQuad;
private Material _material;
private Camera _camera;
// Start is called before the first frame update
void Start()
{
_textureQuad = GameObject.CreatePrimitive(PrimitiveType.Quad);
_textureQuad.GetComponent<MeshRenderer>().material = _material;
_textureQuad.SetActive(true);
_camera = GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
float farPlane = _camera.farClipPlane;
float pos = (_camera.nearClipPlane + 10.0f);
_textureQuad.transform.position = _camera.transform.position + _camera.transform.forward * pos;
_textureQuad.transform.LookAt(_camera.transform.position);
_textureQuad.transform.forward *= -1;
float h = (Mathf.Tan(_camera.fieldOfView * Mathf.Deg2Rad * 0.5f) * pos * 2f);
_textureQuad.transform.localScale = new Vector3((float)h * _camera.aspect, (float)h, 1);
}
}
我们主要是看一下Updata函数中的操作,
1、首先我们先把quad的位置沿着相机的z轴方向,前进。
2、我们使用lookat旋转,跟摄像头保持一样的角度。
3、我们在把quad的forward方向指向摄像头。
4、根据fov与aspect计算出来scale比例。