Introduction
In this article, we will discuss Lerp GameObject forward & Backward of a 3D object using C# scripts in Unity.
Prerequisite
Unity environment version 2019.3.0f6
Create the Project
In the Unity menu, go to GameObject > 3D Object > Cube. A cube is added to the SampleScene in the Hierarchy tab
Rescale the cube size in Scene View
Click on the "GameObject" menu in the menu bar. Select 3D objects and pick the "cube" option. The cube will be added to the scene View
Select the cube and set the position in Scene View
Create an Empty Gameobject
Select the Game Object >> Create an empty GameObject.
Select the empty GameObject on click (Ctrl + D). Create a duplicate GameObject
Rename all the objects used for the scene as: Floor, Player, StartPoint, and EndPoint.
Set the StartPosition in Scene View.
Set the EndPosition in Scene View.
Create a Folder
Right-click on Assets. Select Create >> Folder.
Rename the Folder as Materials
Create a Material
Right-click on Assets. Select Create >> Material.
Rename the material as Floor and Player.
Drag and drop the floor and player material. The color of the cube will be changed into the colors of the floor and player.
Create a C# Script
Right-click on Assets. Select Create >> C# script.
Rename the Scripts as Lerper
Double click on the Lerper script. The MonoDevelop-Unity editor will open up.
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Lerper: MonoBehaviour {
- public Transform startPos, endPos;
- public bool repeatable = false;
- public float speed = 1.0 f;
- public float duration = 3.0 f;
- float startTime, totalDistance;
-
- IEnumerator Start() {
- startTime = Time.time;
- totalDistance = Vector3.Distance(startPos.position, endPos.position);
- while (repeatable) {
- yield
- return RepeatLerp(startPos.position, endPos.position, duration);
- yield
- return RepeatLerp(endPos.position, startPos.position, duration);
- }
- }
-
- void Update() {
- if (!repeatable) {
- float currentDuration = (Time.time - startTime) * speed;
- float journeyFraction = currentDuration / totalDistance;
- this.transform.position = Vector3.Lerp(startPos.position, endPos.position, journeyFraction);
- }
- }
- public IEnumerator RepeatLerp(Vector3 a, Vector3 b, float time) {
- float i = 0.0 f;
- float rate = (1.0 f / time) * speed;
- while (i < 1.0 f) {
- i += Time.deltaTime * rate;
- this.transform.position = Vector3.Lerp(a, b, i);
- yield
- return null;
- }
- }
- }
Save the program.
Drag and drop the Lerper script onto the Player.
Call the Start & End Position onto Lerper Scripts in Scene View.
Set the Speed and Duration to Lerper scripts in Scene View.
Click on the Play button to see Lerper Position of a 3D object in run time:
Summary
I hope you understood how to perform Lerp GameObject forward & Backward of a 3D object using C# scripts in Unity.