How do I make a character "Jump" back when hit (collide)

I’m trying to make my character (it’s a 2D side scroller) “jump” back a bit when they come in contact with an enemy character. The code I’m using makes them “warp” back – that is, they do not move fluidly back, they suddenly appear further back.

function GotHit (){
		var newPos = transform.position.x - 200;
		transform.position.x = Mathf.Lerp(transform.position.x, newPos, .5);
}

Any thoughts on how to make this work as I would like?

Thanks!

Lerp is usefull but you are only using it once with last variable set to .5f. This means you wont get smooth effect but your animation will “jump” back for half (because you put .5f as last parameter) of the set ammount and then nothing else will happen.

Create another character state (isJumpingBack for instance, but probably you have single state variable and enum of states). Then in update SUM deltaTime into another variable (for instance timeInJumpBack or maybe you have general variable already eg. timeInState) and use
if(timeInJumpBack < .5f)

transform.position.x = Mathf.Lerp(transform.position.x, newPos, timeInJumpBack / 0.5f)

However, this will get you kinda lame effect of sliding back. Try it also like this or find some other log like shaped curve function to put into lerp.

if(timeInJumpBack < .5f)

transform.position.x = Mathf.Lerp(transform.position.x, newPos, Mathf.Pow(timeInJumpBack / 0.5f, .5f)