Search Unity

Control Object with Noise

Discussion in 'Cinemachine' started by CDF, Feb 28, 2019.

  1. CDF

    CDF

    Joined:
    Sep 14, 2013
    Posts:
    1,311
    Hey guys, thought I'd share this little script. I wanted to move and rotate an object using Cinemachine's noise functions.

    Might be a better way? But working for my purposes :)

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using Cinemachine;
    4.  
    5. [RequireComponent(typeof(CinemachineBasicMultiChannelPerlin))]
    6. public sealed class CinemachineNoiseObject : MonoBehaviour {
    7.  
    8.     [Tooltip("Determines whether position from noise is added to the current Transform")]
    9.     public bool additivePosition = false;
    10.  
    11.     [Tooltip("Determines whether rotation from noise is added to the current Transform")]
    12.     public bool additiveRotation = false;
    13.  
    14.     [System.NonSerialized] private CameraState state;
    15.     [System.NonSerialized] private CinemachineBasicMultiChannelPerlin noise;
    16.  
    17.     private void Awake() {
    18.  
    19.         noise = GetComponent<CinemachineBasicMultiChannelPerlin>();
    20.     }
    21.  
    22.     private void OnEnable() {
    23.  
    24.         state = CameraState.Default;
    25.     }
    26.  
    27.     private void Update() {
    28.  
    29.         //get starting position and rotation
    30.  
    31.         state.RawPosition = transform.position;
    32.         state.RawOrientation = transform.rotation;
    33.  
    34.         //if not additve, then remove the last correction
    35.  
    36.         if (!additivePosition) {
    37.  
    38.             state.RawPosition -= state.PositionCorrection;
    39.         }
    40.  
    41.         if (!additiveRotation) {
    42.  
    43.             state.RawOrientation *= Quaternion.Inverse(state.OrientationCorrection);
    44.         }
    45.  
    46.         //reset correction
    47.  
    48.         state.PositionCorrection = Vector3.zero;
    49.         state.OrientationCorrection = Quaternion.identity;
    50.  
    51.         //apply noise
    52.  
    53.         noise.MutateCameraState(ref state, Time.deltaTime);
    54.  
    55.         transform.SetPositionAndRotation(state.CorrectedPosition, state.CorrectedOrientation);
    56.     }
    57. }
    58.  
    EDIT - don't extend from CinemachineBasicMultiChannelPerlin, otherwise this shows up in noise drop down
     
    Last edited: Feb 28, 2019