How to do it...

To use the Lerp() function for animating objects, follow these steps:

  1. First we need to create some objects to work with. Create a new Image (go to Game ObjectUIImage). Name it RedDot (you can add a circle sprite to it or leave it as it is). Change its color to red.
  2. Set the RedDot position to (0,0,0) and its Anchor Preset to middle center, as shown in the following screenshot:
RedDot's Anchor Preset
  1. Create another Image and name it BlueDot. Change its color to blue.
  2. Change its Anchor Preset to bottom left.
  3. Create a new C# script and name it LerpNormal.cs. In this script's Update() function, we interpolate a float posX variable's value from the public float minPos to public float maxPos value. We use a floattimer that increases to the value of 1 in time. If its value reaches 1, it starts to decrease to 0. If it reaches 0, it starts to increase again. Finally, we set the localPosition of RedDot rectTransform using our interpolated posX value. The posY and posZ values are set in the Start() function and are constant:
      if (timer > 1f) 
      { 
          lerpDir = -1f; 
      } 
      else if (timer < 0f) 
      { 
          lerpDir = 1f; 
      } 
 
      timer += lerpDir*Time.deltaTime * speed; 
 
      posX = Mathf.Lerp(minPos, maxPos, timer); 
 
      rectTransform.localPosition = new Vector3(posX, posY, 
                                  posZ); 
  1. Assign the script to the RedDot game object.
  2. Create another C# script and call it LerpContinuous.cs. In this script's Update() function, we interpolate the position of the BlueDot with itself and the mouse cursor position. We do it every frame. In the Lerp() function, we use the Time.deltaTime value multiplied by a public float speed variable:
      rectTransform.position = 
                  Vector3.Lerp(rectTransform.position, 
                  Input.mousePosition, Time.deltaTime * 
                  speed); 
  1. Assign the script to the BlueDot 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.129.42.134