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?
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)
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:
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)