意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

【Unity开发小技巧】Unity相机跟随多种实现方式总结

来源:恒创科技 编辑:恒创科技编辑部
2022-10-01 11:54:04


目录

​​一:设置目标物为相机的父节点​​


【Unity开发小技巧】Unity相机跟随多种实现方式总结

​​二:常规设置固定相对向量偏移​​

​​三:添加旋转角度​​

​​四: 第三背后视角​​


欢迎加入Unity业内qq交流群:95618748

一:设置目标物为相机的父节点

描述:最简单,最基础,效果最不理想,锁死跟随视角

【Unity开发小技巧】Unity相机跟随多种实现方式总结_实时计算

二:常规设置固定相对向量偏移

描述:推荐指数***,代码实现简,效果比较生硬

【Unity开发小技巧】Unity相机跟随多种实现方式总结_实时计算_02

public Transform target;
private Vector3 offset;
void Start()
{
//设置相对偏移
offset = target.position - this.transform.position;
}
void Update()
{
//更新位置
this.transform.position = target.position - offset;
}
三:添加旋转角度

描述:推荐指数***,在二的基础上添加距离差值和旋转角度差值,效果流畅

【Unity开发小技巧】Unity相机跟随多种实现方式总结_旋转角度_03

si

private Vector3 offset;//相机相对于玩家的位置
public Transform target;
private Vector3 pos;
public float speed = 2;
private void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
pos = target.position + offset;
this.transform.position = Vector3.Lerp(transform.position, pos, speed * Time.deltaTime);//调整相机与玩家之间的距离

Quaternion angel = Quaternion.LookRotation(target.position - transform.position);//获取旋转角度
transform.rotation = Quaternion.Slerp(transform.rotation, angel, speed * Time.deltaTime);
}
四: 第三背后视角

描述:推荐指数*****,流畅参数可调。对相机的位置实时计算

【Unity开发小技巧】Unity相机跟随多种实现方式总结_父节点_04

public Transform target;
public float distanceUp = 10f;//相机与目标的竖直高度参数
public float distanceAway = 10f;//相机与目标的水平距离参数
public float smooth = 2f;//位置平滑移动插值参数值
public float camDepthSmooth = 20f;

void Update()
{
// 鼠标轴控制相机的远近
if ((Input.mouseScrollDelta.y < 0 && Camera.main.fieldOfView >= 3) || Input.mouseScrollDelta.y > 0 && Camera.main.fieldOfView <= 80)
{
Camera.main.fieldOfView += Input.mouseScrollDelta.y * camDepthSmooth * Time.deltaTime;
}
}

void LateUpdate()
{
//计算出相机的位置
Vector3 disPos = target.position + Vector3.up * distanceUp - target.forward * distanceAway;

transform.position = Vector3.Lerp(transform.position, disPos, Time.deltaTime * smooth);
//相机的角度
transform.LookAt(target.position);
}
上一篇: 租用美国服务器:潜在的风险与应对策略。 下一篇: MongoDB 5.0 扩展开源文档数据库操作