An application of clamp

Get help using Construct 2

Post » 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
60
S
36
G
23
Posts: 342
Reputation: 17,159

Post » 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.
Image ImageImage
B
169
S
50
G
169
Posts: 8,286
Reputation: 108,216

Post » 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,650

Post » Fri Sep 18, 2015 11:32 pm

Oh, that's pretty neat! Thanks for explaining that @newt and @ramones !
B
60
S
36
G
23
Posts: 342
Reputation: 17,159


Return to How do I....?

Who is online

Users browsing this forum: htmlgames and 13 guests