How to do it...

To use math for animating a curve, follow these steps:

  1. Create an empty game object.
  2. Add a Line Renderer component to it.
  3. Create a new material of your liking and assign it to the Line Renderer.
  4. Make sure the Use World Space option in the Line renderer component is not selected (we will use local coordinates in this example as it makes it slightly easier to position the Line Renderer in the camera).
  5. Change the Start Width and End Width of the Line Renderer to 0.2 to make the line thinner.
  6. Create a new C# script and name it MathAnim.cs. In this script's Start() function, we set the number of points of the Line Renderer using the SetVertices() method:
      positions = new Vector3[linePoints]; 
      lRenderer = GetComponent<LineRenderer>(); 
      if (lRenderer != null) 
      { 
          lRenderer.SetVertexCount(linePoints); 
      } 
  1. Then, in the Update() function, we call the void SetLinePositions() function and we move the game object so that the line center is at the (0, 0, 0) point:
      transform.position = new Vector3(-0.5f 
                          * lineLenght, 0f, 0f); 
      SetLinePositions(); 
  1. In the void SetLinePositions() function, use the Mathf.Sin() and Mathf.Cos() functions to calculate the point's Y and Z positions. We set the line points positions with the SetPositions() function. We also use a simple timer to introduce time into our formula. We have two timers: timerY and timerZ. The first one works for the Y position values and the second one for Z position values. We also have the public float variables for controlling frequencyYfrequencyZamplitudeY, and amplitudeZ. The X positions of the line points are set in equal distances so that the total length of the line is equal the public float lineLength variable's value:
      if (lRenderer == null) 
      { 
          return; 
      } 
 
      timerY += Time.deltaTime * speedY; 
      timerZ += Time.deltaTime * speedZ; 
 
      for (int i = 0; i < positions.Length; i++) 
      { 
          positions[i].x = lineLenght * (float)i / 
                      (float)positions.Length; 
     
          positions[i].y = amplitudeY * Mathf.Sin(frequencyY 
                  * ((2f*Mathf.PI * (float)i / 
                  (float)positions.Length) + timerY)); 
     
          positions[i].z = amplitudeZ * Mathf.Cos(frequencyZ 
                  * ((2f * Mathf.PI * (float)i / 
                  (float)positions.Length) + timerZ)); 
      } 
      lRenderer.SetPositions(positions); 

  1. Attach the script to our game object.
  2. Play the game to see the effect.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.91.24