Unity3d CarSmoothFollow

1821阅读 0评论2011-07-15 matthew_1983
分类:嵌入式

Here's another smooth camera script. Designed to follow a car smoothly and give you the ability to zoom out when the car is moving. Hope someone makes use of it.

  1. using UnityEngine;
  2. using System.Collections;

  3. public class CarSmoothFollow : MonoBehaviour {
  4.     
  5.     public Transform target;
  6.     public float distance = 20.0f;
  7.     public float height = 5.0f;
  8.     public float heightDamping = 2.0f;

  9.     public float lookAtHeight = 0.0f;
  10.     
  11.     public Rigidbody parentRigidbody;

  12.     public float rotationSnapTime = 0.3F;
  13.     
  14.     public float distanceSnapTime;
  15.     public float distanceMultiplier;
  16.     
  17.     private Vector3 lookAtVector;

  18.     private float usedDistance;
  19.     
  20.     float wantedRotationAngle;
  21.     float wantedHeight;
  22.     
  23.     float currentRotationAngle;
  24.     float currentHeight;
  25.     
  26.     Quaternion currentRotation;
  27.     Vector3 wantedPosition;

  28.     private float yVelocity = 0.0F;
  29.     private float zVelocity = 0.0F;

  30.     void Start () {
  31.     
  32.         lookAtVector = new Vector3(0,lookAtHeight,0);
  33.         
  34.     }

  35.     void LateUpdate () {

  36.         wantedHeight = target.position.y + height;
  37.         currentHeight = transform.position.y;
  38.         
  39.         wantedRotationAngle = target.eulerAngles.y;
  40.         currentRotationAngle = transform.eulerAngles.y;

  41.         currentRotationAngle = Mathf.SmoothDampAngle(currentRotationAngle, wantedRotationAngle, ref yVelocity, rotationSnapTime);

  42.         currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

  43.         wantedPosition = target.position;
  44.         wantedPosition.y = currentHeight;
  45.     
  46.         usedDistance = Mathf.SmoothDampAngle(usedDistance, distance + (parentRigidbody.velocity.magnitude * distanceMultiplier), ref zVelocity, distanceSnapTime);
  47.         
  48.         wantedPosition += Quaternion.Euler(0, currentRotationAngle, 0) * new Vector3(0, 0, -usedDistance);

  49.         transform.position = wantedPosition;
  50.         
  51.         transform.LookAt(target.position + lookAtVector);
  52.         
  53.     }
  54.     
  55. }
上一篇:C++ ProtoBuf小结
下一篇:Yield使用方法