Tuesday, 6 May 2014

Lerps

To begin with, i found lerps fiddly to work with, but i have got my head around them now. They are really useful for moving objects in 3D space. Before, if i wanted to move something through code and have it not instantly move there, i would write something like:

if(this.x < 500)

{
 this.x += 10;
}
//This wont actually work but helps to explains my point

Lerps are more efficient and easier to manage.

transform.position = Vector3.Lerp(StartPoint, EndPoint, Time.deltaTime * Speed);

The object moves from the StartPoint to the EndPoint, Time.deltaTime is the time frame and Speed is how quick the object moves.
StartPoint and EndPoint need to be Vector3s (or Vector2s with a Vector2.Lerp). The logical thing to would be to use the objects current position for StartPoint. The benefit of using a variable for the EndPoint it that it can then be edited outside of the current class.

Here is how i have been using lerps:

private var endpoint : Vector3

function Update ()
{
  if(transform.position != endpoint)
  {
   transform.position = Vector3.Lerp(transform.position, endpoint, Time.deltaTime * 10);
  }
}



transform.position != endpoint Means that the lerp is only active when the endpoint var has changed.

Another benefit that i have discovered with lerps over moving an object position by a set amount, the object will always finish at the endpoint even if the var changes before the object reaches it. for example if a player clicks too fast, I have had issues with objects not moving the full amount.

I struggled to get rotation lerps to work. I could not get the example from from Unity3d.com to work for me. Their exemple is:

var from : Transform; 
var to : Transform; 
var speed = 0.1; 
function Update () 

  transform.rotation = Quaternion.Lerp (from.rotation, to.rotation, Time.time * speed); 
}

But after looking at what other people were suggesting on the forums, i managed to get the same effect from the following lines of code.

private var to : Quaternion;

function Start ()

{
  to = Quaternion.Euler(0,-90,0);
}

function Update ()
{
  transform.rotation = Quaternion.Lerp(transform.rotation, to, Time.time * 0.1);
}

No comments:

Post a Comment