smooth transition of character controller using Lerp function

hi guys, still a beginner. Ive seen similar questions here, but none that deal with the transition of a character controller. I am using the standard assets first person controller, and my aim is to make the character jump back when he gets hurt, like a flinch motion. Form what i gather i need to use the Lerp function to gradually move a gameobject form one point (Vector) to another point (Vector). The transition is not between to specific points, like gameObject a to gameObject b. So i am updating the current position of the player in the update function, and also updating the position o want him to end up when he gets hit (ControllerCollderHit), which is X units backwards from his current position. But he just instantly moves to the new position and there is no actual visible transition. heres the code.

var currentPosition : Vector3;
var FlichPosition : Vector3 ;
var beenHit : boolean ;

function Start () {

	beenHit = false;	

}

function Update () {

	currentPosition = transform.position; // need to update position every frame. 
	FlichPosition = currentPosition -= transform.forward * 5;
	
	if (beenHit)
	{
		transform.position = Vector3.Lerp (currentPosition, FlichPosition, Time.deltaTime * 1);
		beenHit = false;
	}

}

function OnControllerColliderHit (hit : ControllerColliderHit){
	if (hit.gameObject.collider.name == "FireElement")
	{	
		beenHit = true ;
		Debug.Log("hit fire");
	}
}

so what have i done wrong guys? :slight_smile:

thanks alot

Your main issue with the immediate transport is on line 14:

 FlichPosition = currentPosition -= transform.forward * 5;

Note you have two ‘=’ signs in the statement. The result is that FlitPosition and currentPosition are both getting set to the same value, so no matter what you put in your Lerp(), you will always transport. There are some additional issues as mentioned above. The use of Time.deltaTime will work. It is a very common way of using Lerp(). It results in an eased movement, not a linear movement as Lerp() would produce if you used it as @PAEvenson suggests.

Here is an alternate script to do what you are trying to do here:

#pragma strict
var speed = 3.0;
private var destPosition : Vector3;
private var beenHit = false;
 
function Start() {
    destPosition = transform.position;
}
 
function Update () {

	if (beenHit) {
    	transform.position = Vector3.Lerp (transform.position, destPosition, Time.deltaTime * speed);
    	if (transform.position == destPosition)
    		beenHit = false;
    }
}
 
function OnControllerColliderHit (hit : ControllerColliderHit){
    if (hit.gameObject.collider.name == "FireElement") {  
      destPosition = transform.position - transform.forward * 5.0;
      beenHit = true; 
    }
}

Note if you are looking for a movement that is not eased, replace the Lerp() with MoveTowards().