Unity 3D--摄像机平滑跟随(方法二)

111 篇文章 3 订阅
  1. public Transform target = null;  
  2.     public float height = 1f;  
  3.     public float positionDamping = 3f;  
  4.     public float velocityDamping = 3f;  
  5.     public float distance = 4f;  
  6.     public LayerMask ignoreLayers = -1;  
  7.   
  8.     private RaycastHit hit = new RaycastHit();  
  9.   
  10.     private Vector3 prevVelocity = Vector3.zero;  
  11.     private LayerMask raycastLayers = -1;  
  12.       
  13.     private Vector3 currentVelocity = Vector3.zero;  
  14.       
  15.     void Start()  
  16.     {  
  17.         raycastLayers = ~ignoreLayers;  
  18.     }  
  19.   
  20.     void FixedUpdate()  
  21.     {  
  22.         currentVelocity = Vector3.Lerp(prevVelocity, target.root.rigidbody.velocity, velocityDamping * Time.deltaTime);  
  23.         currentVelocity.y = 0;  
  24.         prevVelocity = currentVelocity;  
  25.     }  
  26.       
  27.     void LateUpdate()  
  28.     {  
  29.         float speedFactor = Mathf.Clamp01(target.root.rigidbody.velocity.magnitude / 70.0f);  
  30.         camera.fieldOfView = Mathf.Lerp(55, 72, speedFactor);  
  31.         float currentDistance = Mathf.Lerp(7.5f, 6.5f, speedFactor);  
  32.           
  33.         currentVelocity = currentVelocity.normalized;  
  34.           
  35.         Vector3 newTargetPosition = target.position + Vector3.up * height;  
  36.         Vector3 newPosition = newTargetPosition - (currentVelocity * currentDistance);  
  37.         newPosition.y = newTargetPosition.y;  
  38.           
  39.         Vector3 targetDirection = newPosition - newTargetPosition;  
  40.         if(Physics.Raycast(newTargetPosition, targetDirection, out hit, currentDistance, raycastLayers))  
  41.             newPosition = hit.point;  
  42.           
  43.         transform.position = newPosition;  
  44.         transform.LookAt(newTargetPosition);  
  45.           
  46.     }  


脚本直接赋给摄像机,添加Target就可以。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值