Unity 相机追踪人物功能实现(解决被障碍物遮挡问题)
默认跟随代码,绑定到相机上
public Transform player;
private Vector3 distance;
private void Awake(){
distance = transform.position - player.transform.position;
}
public void Update(){
transform.position = distance + player.transform.position;
}
解决被障碍物遮挡问题,修改
public void Update(){
// transform.position = distance + player.transform.position;
Vector3 beginPos = distance + player.transform.position;
Vector3 endPos = distance.magnitude * Vector3.up + player.transform.position;
Vector3 pos1 = Vector3.Lerp(beginPos, endPos, 0.25f);
Vector3 pos2 = Vector3.Lerp(beginPos, endPos, 0.5f);
Vector3 pos3 = Vector3.Lerp(beginPos, endPos, 0.75f);
Vector3[] posArray = new Vector3[] { beginPos, pos1, pos2, pos3, endPos };
Vector3 targetPos = posArray[0];
for(int i = 0; i < 5; i++)
{
RaycastHit hitInfo;
if (Physics.Raycast(posArray[i], player.transform.position - posArray[i],out hitInfo)){
if (hitInfo.collider.tag != TAGS.player)
{
continue;
}
else
{
targetPos = posArray[i];
break;
}
}
else
{
targetPos = posArray[i];
break;
}
}
Quaternion nowRotation = transform.rotation;
transform.LookAt(player.transform);
transform.rotation=Quaternion.Lerp(nowRotation, transform.rotation, rotateSpeed * Time.deltaTime);
transform.position = Vector3.Lerp(transform.position, targetPos, moveSpeed * Time.deltaTime);
}