unity 摄像机跟随主角移动
程序员文章站
2023-12-27 10:38:21
...
摄像机跟随(普通版)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
private Transform playerTrans;
private Vector3 offset;
private void Awake()
{
playerTrans = GameObject.FindWithTag(Tags.Player).transform;
offset = transform.position-playerTrans.position;
offset = new Vector3(0, offset.y, offset.z);
}
void Update()
{
transform.position = Vector3.Lerp(transform.position, playerTrans.position + offset, Time.deltaTime*10);
}
}
我们平常用到的摄像机跟随主角是这样的,但是当主角移动到某个物体的后面时,虽然摄像机是跟随了,但是我们这个时候看不到主角了,因为主角已经被物体挡住了,那么这个时候我们该怎么解决呢?
摄像机跟随(改进版)
如上图所示,游戏物体挡住了我们的视野,但是我们可以通过这样计算出points的五个位置,从第一个位置开始发射射线,如果射线检测到的物体是Player,则摄像机就在第一个位置的方向上跟随物体,如果第一个位置检测不到Player,就从第二个位置发射射线再次进行检测,以此类推,直到检测到Player位置,此时摄像机就平缓移动到那个位置进行跟随Player。
代码的实现过程如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
private Transform playerTrans;
private Vector3 offset;
private void Awake()
{
playerTrans = GameObject.FindWithTag(Tags.Player).transform;
offset = transform.position-playerTrans.position;
offset = new Vector3(0, offset.y, offset.z);
}
void Update()
{
Vector3 startPos = playerTrans.position + offset;
Vector3 endPos = playerTrans.position + offset.magnitude * Vector3.up;
Vector3[] points = new Vector3[]
{
startPos,
Vector3.Lerp(startPos,endPos,0.25f),
Vector3.Lerp(startPos,endPos,0.5f),
Vector3.Lerp(startPos,endPos,0.75f),
endPos
};
Vector3 target = points[0];
for (int i = 0; i < points.Length; i++)
{
RaycastHit hit;
if (Physics.Raycast(points[i], playerTrans.position - points[i], out hit))
{
if (hit.collider.tag == Tags.Player || hit.collider.tag == Tags.Camera || hit.collider.tag == Tags.Laser)
{
target = points[i];
break;
}
}
else
{
target = points[i];
break;
}
}
transform.position = Vector3.Lerp(transform.position, target, Time.deltaTime * 10);
Quaternion rotate = transform.rotation;
transform.LookAt(playerTrans.position);
transform.rotation = Quaternion.Lerp(rotate, transform.rotation, Time.deltaTime * 10);
}
}