There must be a neat way to express this

I often find myself writing (coroutine) code that does something like this:

if (value < target) {
    value += speed * Time.deltaTime;
    someParameter.value = value;
    if (value >= target)
        yield break;
    else
        yield return null;
}
else if (value > target) {
    value -= speed * Time.deltaTime;
    someParameter.value = value;
    if (value <= target)
        yield break;
    else
        yield return null;
}

I hate that “if” statement, but it seems necessary because I need to know whether I’m doing =< or >=. I’m sure there must be a more compact way of expressing this?

You want to lerp something towards a target with a speed? Why dont you just do Mathf.MoveTowards in your coroutine, until your value is approx. equal to target?

2 Likes

Try something like this.

float dist = target - value;
float delta = speed * Mathf.Sign(dist) * Time.deltaTime;
value += delta;

if(Mathf.Abs(delta) > Mathf.Abs(dist))
  yield return null;
else
  yield break;
1 Like

Hey didn’t know about that function! That’s exactly what I was looking for :slight_smile: