Efficiently approaching zero

Edit: This post is not about a problem that I cannot solve. I know the solution, I’m just asking if there’s a simpler way to solve it. Just wondering if it’s possible, that’s all.


I’ve made a custom camera script that allows me to pan the camera vertically using the Up and Down arrow keys, along with horizontally with the Left and Right arrow keys.

I’ve also made it so that if the player is holding neither Up nor Down, the camera will begin panning vertically back to zero. This is the code responsible for panning back to zero:

X -= math.sign(X)*panPerFrame

(X is the camera’s X rotation, and panPerFrame is how much the camera will rotate each frame according to delta time.)

The issue with this is rather obvious: 99% of the time, X will never hit exactly zero. Instead, it’ll try to subtract on one frame, overshoot zero, then try to add on the next frame, overshooting again. This repeats infinitely and causes the camera to shake violently.

I could fix this with an ‘if’ statement, but it feels like a really inefficient solution. Is there a better way to fix this problem?

1 Like

math.clamp?

1 Like
if X > 0 then
X = math.max(X - panPerFrame, 0)
else
X = math.min(X + panPerFrame, 0)
end
1 Like

My goal here is to find something simpler than an if statement, if possible

That sets a min and max right? In my case zero is right in the middle of the range of values X can be.

I found this formula on stack overflow for reaching a target with iteration:
image

Since your target is 0, rewriting it gives

X += -X * panPerFrame

Try that and see if it gets better.

This works, but it creates an easing effect (gets slower as it approaches zero) that I don’t want. Preferably the camera will pan at the same speed the entire time. I should’ve clarified this in my post, sorry

Why? it’s only if statement, you only overcomplicate your code, sometimes simplier is most efficient, also you don’t need math which is usually heavier than if statement

EDIT: You can use conditions to set variable

X = X > 0 and math.max(X- panPerFrame, 0) or math.min(X + panPerFrame, 0)

In some cases using an if statement rather than more math is better

Didn’t mean to imply that a math function would be faster. I was just asking if there was anything faster than an if statement. I’m more than happy to just use an if statement, this post was mainly out of curiosity

You can do it any other way. As you can see on this graph:
image
you can only approach the value, cant cut it off if you want it linearly. An if statement would be best here. If statements are less clunky than you think, even a lot less heavy than some functions from math. (this image is bad but you get the point)

Fair enough. Marking this as the solution

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.