Advertisement
SvOzMaS

HeadBobber

Oct 22nd, 2018
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. /// <summary>
  4. /// HeadBobber from: http://wiki.unity3d.com/index.php/Headbobber
  5. /// Modifications: Translation from JS to C# and SmoothDamp movement options added
  6. /// </summary>
  7.  
  8. public class HeadBobber : MonoBehaviour {
  9.  
  10.     private float timer = 0.0f;
  11.     public float bobbingSpeed = 0.18f;
  12.     public float bobbingAmount = 0.2f;
  13.     public float midpoint = 2.0f;
  14.     Vector3 targetPos;
  15.  
  16.     public bool smooth = true;
  17.     private Vector3 velocity = Vector3.zero;
  18.     public float smoothTime = 0.3F;
  19.  
  20.     void Update()  {
  21.  
  22.         float waveslice = 0.0f;
  23.         float horizontal = Input.GetAxis("Horizontal");
  24.         float vertical = Input.GetAxis("Vertical");
  25.        
  26.         if (Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0) {
  27.             timer = 0.0f;
  28.         }
  29.         else {
  30.             waveslice = Mathf.Sin(timer);
  31.             timer = timer + bobbingSpeed;
  32.  
  33.             if (timer > Mathf.PI * 2f) {
  34.                 timer = timer - (Mathf.PI * 2f);
  35.             }
  36.         }
  37.  
  38.         if (waveslice != 0f) {
  39.             float translateChange = waveslice * bobbingAmount;
  40.             float totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
  41.  
  42.             totalAxes = Mathf.Clamp(totalAxes, 0f, 1.0f);
  43.             translateChange = totalAxes * translateChange;
  44.             targetPos.Set(transform.localPosition.x, midpoint + translateChange, transform.localPosition.z);
  45.         }
  46.         else {
  47.             targetPos.Set(transform.localPosition.x, midpoint, transform.localPosition.z);
  48.         }
  49.  
  50.         if (smooth) {
  51.             transform.localPosition = Vector3.SmoothDamp(transform.localPosition, targetPos, ref velocity, smoothTime);
  52.         }
  53.         else {
  54.             transform.localPosition = targetPos;
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement