# Bar increases the more distant you are, when expected behaviour is to be slower

Hello!
I’m making a detection system, and I’m having quite a hard time making the bar speed based on distance.
What I had planned is, to make so the more distant you are from the bar, the slower it goes up, and the more closer, faster.
Currently what I have is the opposite if what I mentioned above:

This is the code that controls it:

``````-- minDetection is 0, maxDetection is 100
detectionRate = math.clamp(
minDetection + (maxDetection - minDetection) * (distance / maxDistance),
0,
1
)
detectionBarGuiBar.Size = UDim2.new(1,0,-(detection/maxDetection),0)
``````

Does anyone know what’s wrong in the math?

The problem is this part:

The greater the distance, the larger it will get because the number that is being divided will increase. Maybe try this, which will get the opposite of the distance. If they were 20 studs away the new code will calculate it for 0.8, and if they are 90 studs away it will calculate it for 0.1:

``````detectionRate = math.clamp(
minDetection + (maxDetection - minDetection) * (-(distance-maxDetection) / maxDistance),
0,
1
)
detectionBarGuiBar.Size = UDim2.new(1,0,-(detection/maxDetection),0)``````
1 Like

It did really work, however, the difference between being close and far isn’t very noticeable because the max distance is 50 studs, so, is there any way to change the the max and min values?
For example, if 20 studs away is 0.8 and 90 studs away is 0.1, can you make them evaluate to 1.5 and 0.02?

Oh I see what you are saying, give me one second to think about it. Alright I sort of figured it out using a graph, but I might mess it up when I try to write it out. I’m going to test it in studio and I’ll get back to you when its done.

1 Like

I’m stumped I’m sorry. I can ask my teacher tommorow and get back to you after that.

1 Like

Me wishing I knew how to code something even close to this lol.

Not wanting to advertise or anything, but I’m actually making a tutorial on a stealth system here, some stuff already works so you could check it out if you want to (＾▽＾)

Nice, I’ve been looking for something like that for forever lol.