Lerping on click on android screen.

void Update ()
{

foreach (Touch touch in Input.touches)

{

if (touch.phase==TouchPhase.Began)

	{
			if(touch.position.x<125.0f)
			{
				if(position.x<position1.x)
				{
                             transform.position = Vector3.Lerp(startMarker.position, endMarker.position,Time.deltaTime);
					        Debug.Log("transform's position"+transform.position);}}}

(Implementing a multitouch)
Hello friends what i want to do is on click on the screen on left half( which is why i’m using the touch position condition.)the object should lerp to the right half ,what’s wrong with this is the touch phase condition i have to use it to start the touch but than it does’nt let the lerp run for full update as it turns out to be false.

Hi,

With your touch.position.x condition, set a bool to true so Unity remembers that it needs to lerp:

if (touch.position.x < 125){
   lerping = true;
}

Now that you know you have to lerp (since boolean is set to true), put your lerping code under this condition:

if (lerping) {
   transform.position = ... ;
}

So whenever you touch the right part of your screen, boolean goes to true and allows lerping. Last but not least, you wan’t the lerping boolean to be set back to false when the movement is done but you’re still asking Unity to lerp:

if (transform.position == endMarker.position && lerping){
   lerping = false;
}

Full Update() code would be:

if (touch.position.x < 125){
   lerping = true;
}

if (lerping){
   transform.position = ... ;
}

if (transform.position == endMarker.position && lerping){
   lerping = false;
}

BUT ! (There’s always a but :p)


Using Lerp to move from a position to an other is an abusive way, you should (must) use Vector3.MoveTowards() that is made for what you want !

Secondly, using

transform.position == endMarker.position
as a condition is very risky. You will never have the exact Vector3 that is equal to the other Vector3 position, you may never have the condition to be true hence never set your boolean back to true ! That’s why you should use MoveTowards. Other reason would be that Lerp does not return a constant speed unless you put some very specific arguements instead of Time.deltaTime …

So:

  • Use MoveTowards instead of Lerp

  • Be careful with your end of movement condition