- Home /
How to create a sine function with cutoff peaks and troughs
I want to create a saw hazard for my current game and I want the arm to move back in forth similar to capturing the output of a sine function like this movementDistance * Mathf.Sin(counter * movementSpeed); except I want the "edges" of the sine function to be capped off (compressed) like this 
(original source: https://www.youtube.com/watch?v=yj53Q-pisbw&t=87s&ab_channel=CSGuitars between 0:48 and 0:57)
I'm aware I could simply use Mathf.Clamp(calculatedValue, -extent, extent) , but this would create drastic stopping and starting at the edges and I'd like to round these edges if possible to make a more realistic slowdown effect for the saw arm. How could I achieve such an effect?
Answer by Hellium · Apr 30, 2021 at 11:29 PM
Simply use an animation curve and use Evaluate instead of the Sin method.
https://docs.unity3d.com/ScriptReference/AnimationCurve.Evaluate.html
 public AnimationCurve Curve; // Define the curve in the inspector
 
 //...
 float value = movementDistance * Curve.Evaluate(counter * movementSpeed);
If you want the curve to be prepopulated with the Sin curve:
 private void OnValidate()
 {
     if(curve.keys.Length == 1)
     {
         curve.RemoveKey(0);
         curve.postWrapMode = WrapMode.Loop;
         curve.AddKey(new Keyframe(0, 0, 1, 1)); // 0, sin(0), sin'(0) = cos(0), sin'(0) = cos(0)
         curve.AddKey(new Keyframe(0.5f * Mathf.PI, 1, 0, 0));
         curve.AddKey(new Keyframe(Mathf.PI, 0, -1, -1));
         curve.AddKey(new Keyframe(1.5f * Mathf.PI, -1, 0, 0));
         curve.AddKey(new Keyframe(2f * Mathf.PI, 0, 1, 1));
     }
 }
Then, add the keys you want in the inspector
So I added your OnValidate code, and tried this in the Update function as well:
  timer += Time.deltaTime;
         if (timer > maxTime)
         {
             timer = 0;
         }
 
         float lValue = movementDistance * lerpCurve.Evaluate(timer * movementSpeed);
 
         transform.position += -transform.up * lValue;
but now the gameobject just slowly drifts into one direction. Did I make a mistake with my code?
      transform.position = -transform.up * lValue;
I tried this but the gameobject just spawned at the origin and didn't move anymore
Your answer
 
 
             Follow this Question
Related Questions
Working out Difference in Rotation 2 Answers
Modify distance with var? 1 Answer
Counter issues, hitting -1? 1 Answer
Raycast - Clamp Math Issue 0 Answers
How to Clamp X-axis Movement only? 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                