Search Unity

Free Head Sway Script

Discussion in 'Made With Unity' started by SideEffect_, Aug 26, 2016.

  1. SideEffect_

    SideEffect_

    Joined:
    Jan 27, 2015
    Posts:
    3
    Hello everyone,
    Yesterday I was looking for a simple and realistic look sway script, but didn't find anything I thought was adequate. Now I've written one, and I thought I'd share it! Feel free to edit it, use it in your game, etc.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. // Attach to object which parents the camera and does not have other scripts affecting the transform
    4. public class LookSway : MonoBehaviour
    5. {
    6.     public const string VerticalAxisKey = "Vertical";
    7.  
    8.     public float HorizontalAmplitude = 0.05f;
    9.     public float VerticalAmplitude = 0.12f;
    10.  
    11.     public float WalkSpeed = 6f;
    12.     public float WalkSpeedMagnitudeMultiplier = 0.025f;
    13.  
    14.     public float BaseSpeed = 1.25f;
    15.  
    16.     private Vector3 movement;
    17.     private float progress;
    18.  
    19.     private void Start()
    20.     {
    21.         movement = Vector3.zero;
    22.     }
    23.  
    24.     private void Update()
    25.     {
    26.         progress = (progress + (Time.deltaTime * BaseSpeed + NormalizedSpeed * WalkSpeed * Time.deltaTime) * (Random.Range(0f, 2f))) % (2 * Mathf.PI);
    27.         movement.x = ((NormalizedSpeed * WalkSpeedMagnitudeMultiplier) + VerticalAmplitude) * Mathf.Cos(progress + Mathf.PI / 2);
    28.         movement.z = ((NormalizedSpeed * WalkSpeedMagnitudeMultiplier) + HorizontalAmplitude) * Mathf.Sin(Mathf.PI / 2 - 2 * progress);
    29.  
    30.         transform.localEulerAngles = movement * 10;
    31.     }
    32.  
    33.     public float NormalizedSpeed
    34.     {
    35.         get
    36.         {
    37.             return Input.GetAxis(VerticalAxisKey);
    38.         }
    39.     }
    40. }
    41.  
    Alternitavely, if you have a Rigidbody attached to your walking script, you could edit the property NormalizedSpeed to be dependent on the Rigidbody's speed rather than the user's input, resulting to something along the lines of

    Code (CSharp):
    1. public float NormalizedSpeed
    2. {
    3.     get
    4.     {
    5.           return _rigidbody.velocity.magnitude / maxWalkSpeed;
    6.     }
    7. }
    8.  
    9.  
    Hope this helps!
     
    Last edited: Aug 26, 2016
    theANMATOR2b likes this.