Clamping Float Value in Javascript [Solved]

Hiya.

Due to circumstance I have been forced to clamp a value in Javascript, now I can’t get this to work.
I have this float value,

public var inAirControlAcceleration : float = 0;

Now, how do I clamp it so it can go no lower than 0 and no higher than 2?
I’ve googled and tried, but I’m obviously overlooking something because I can’t get the syntax right.
(Keeps telling me to add semicolons, even though they’re there)

Unity - Scripting API: Mathf.Clamp This is how you’ll clamp.

Can select the javascript button at the top right if it makes a difference, but it’s pretty much the same thing. You pass in a variable, a low value and a high value and it will always keep it between the two.

2 Likes

Hello.
Yeah, I’ve been trying what is described on that page (usually I get them), but I am a little thrown off by it by how it uses a vector3 and transform position as an example.

inAirControlAcceleration = float(Mathf.Clamp(0.0, 1.0, 3.0), 0.0);

Make something like this and I get errors so I’m doing something wrong, heh.

inAirControlAcceleration = Mathf.Clamp(inAirControlAcceleration, 0f, 2f);
1 Like

The vector3 they use is trying to show an example of how they clamp the position.x portion of the vector3 while leaving y and z as they are. Basically they are showing you that you could keep a player clamped from moving left or right beyond a certain x if you wanted to to keep them on the screen for example.

1 Like

Aaah, thanks. This solved my problem. Thank you for giving the code, LeftyRighty and Barthnann for bothering to explain to me the logic of the example provided.