MathUtil::lerp alpha parameter

Hi there…

I suspect MathUtil::lerp() interpolates between a float to another, those are the first two parameters, so i guess it needs update in order to work isn"t?

I have used update correctly ( because i tested with CCLOG and works printing for ever) and put this:

void myScene::update(float dt){
    CCLOG("%f", MathUtils::lerp(0.0f, 1.0f, 1));
}

But console prints out :

1
1
1
... //for ever

If i change the third argument value to 0, then it prints 0 for ever in the log… So as you can see, no matter what range i put, it keeps printing the alpha value, is like args 0 and 1 are being skipped

What is alpha parameter for?
https://docs.cocos2d-x.org/api-ref/cplusplus/V3.6/de/dbd/classcocos2d_1_1_math_util.html#a684e6e4d2f7bd48dd4a8832bb2e40f0b

That’s not quite how it works. This is the lerp implementation:

float MathUtil::lerp(float from, float to, float alpha)
{
    return from * (1.0f - alpha) + to * alpha;
}

So, if you give it the same values, you’re going to get the exact same result.

As an example of how you would use it, say you’re moving an object along the X axis from X = 0 to X = 1000, and at a specified speed. You would implement it as follows:

float speed = 1.0f;
float destinationX = 1000;

update(float dt)
{
    float currentPosX = obj->getPositionX();
    float newPosX = MathUtils::lerp(currentPosX, destinationX, dt * speed);
    obj->setPositionX(newPosX);
}
2 Likes

thanks, i will give a try and comment later…

ok, i guess i had missunderstood the way this function works…
i was thinking it like MoveTo (from specific point to another), but it work like MoveBy (get the current point, add and repeat untill target is required) isn´t?

once is finished, is there a way to stop update schedule to save performance?
thanks…

MoveTo and MoveBy are both actions, so they are not the same as MathUtil::lerp, which is just a function. The MoveTo and MoveBy actions are given parameters, and then that action is run an object, after which you have no control over them; you can only add or remove actions, and perhaps even pause them, but that is all.

They may be what you need. Have you even looked at the cpp-tests project? Demos of the majority of Cocos2d-x functionality is in there. If you haven’t, then run it, and learn from it.

Well, why use update at all? You can always schedule a function to be called every X period of time, and then unschedule it. Open up CCNode.h, and browse the code. It’ll be pretty obvious how to achieve this once you look at the code.

2 Likes

Hi. There is a very useful and underestimated action in cocos2d-x named ActionFloat.
This action performs like update with more control and you can pause and resume or stop it if you want. Take a look at it.
Actually this action somehow does the same thing as lerp function.

1 Like

That is was i looking for!.., i never thought such thing exists…
Thanks both for solving my problem… both solution were great…