# An application of clamp

Get help using Construct 2

### » Fri Sep 18, 2015 8:18 pm

Hey all, I was reading through the manual and came across "clamp" where x is returned if under a value, above a value - or else return x....

I just don't understand why something would require this. It seems like x is chosen every time from the 3 values. Am I misunderstanding the way this is written? Can someone help me with a practical application of clamp?
B
82
S
48
G
32
Posts: 468
Reputation: 23,663

### » Fri Sep 18, 2015 9:14 pm

Suppose you want a sprite to only move horizontally in a set range of x coordinates, a line if you will.

Always sprite set x to clamp(self.x, 10, 100)

That event will make it stay within 10 to 100 x.
B
179
S
50
G
208
Posts: 8,721
Reputation: 128,810

### » Fri Sep 18, 2015 9:22 pm

If x is less than the lower bound it returns the lower bound, if it's higher than the upper bound then it returns the upper bound and if x is between lower and upper it returns x.

Say you wanted to keep the player health between 0 and 100. You could set
Code: Select all
`playerHealth = clamp(playerHealth + x, 0, 100)`

where x is could be +50 for a health kit or -25 for an enemy attack and the result will always be between 0 and 100. If playerHealth + x goes above 100 then playerHealth gets set to 100. If it goes below 0 then playerHealth gets set to 0.
B
55
S
29
G
19
Posts: 1,520
Reputation: 25,870

### » Fri Sep 18, 2015 11:32 pm

Oh, that's pretty neat! Thanks for explaining that @newt and @ramones !
B
82
S
48
G
32
Posts: 468
Reputation: 23,663