- Home /
Execute function with momentary input
I have this script that is supposed to run a function called "changePos" which Lerps the camera to a different position when the player taps the screen.
The thing is, when the player taps, the camera moves only one unit and then stops. How can I make it so it finishes its lerp?
void Update () {
for (int i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
if (col == Physics2D.OverlapPoint(touchPos))
{
Debug.Log ("Touched");
man.changePos(place, sm);
}
}
}
}
Answer by TheSOULDev · Sep 11, 2017 at 02:28 AM
First off, you should not use Update for input like Touch, use PointerDownHandler and such interfaces. Second of all, Lerp only gives you a value, to make it run for some time you need to continously call it in a loop. The easiest way to do this would be via a Coroutine (so you can stop it if you need it). Something like this:
IEnumerator LerpValue(float Start, float End, float speed)
{
while(Start < End)
{
Start = Mathf.Lerp(Start, End, speed);
yield return null;
}
}
If you want to control it by time spent, you need to do something like this:
IEnumerator LerpValueOverTime(float Start, float End, float overTime)
{
float elapsedTime = 0f;
float StartedFrom = Start;
while(Start < End)
{
Start = Mathf.Lerp(StartedFrom, End, Mathf.Clamp(elapsedTime + Time.deltaTime, 0, overTime) / overTime);
yield return null;
}
}
Hope this cleared things up.
Your answer
Follow this Question
Related Questions
Move A Camera Between Two Points Smoothly 1 Answer
How to move an object from point A to point B with one key press 3 Answers
Smoothing motion with vector3 lerp 3 Answers
interpolate a move variable 0 Answers
Smoothly stop rotating 1 Answer