Page 1 of 1

EOS: How to keep a value from going over a certain limit?

Posted: Mon May 30, 2022 2:18 am
by SpadeSage
Hi there! So basically, I'm making an RPG-Esque web tease using EOS.
I'm wondering how to keep a variable from going below zero, or going too high.

I have two variables in the tease atm, "health" and "maxhealth"
How would I write the code to prevent the health from dipping below zero, and going higher than the maxhealth?

Re: EOS: How to keep a value from going over a certain limit?

Posted: Mon May 30, 2022 4:05 am
by Scilirat
You could write something like

Code: Select all

health = health + regen;
if (health > maxhealth) {health = maxhealth};
This way it will first run the calculation of increasing health and then, if health is greater than whatever maxhealth is set to, health will be brought back down to maxhealth.

For keeping health above a desired value you just have to write the exact same thing but in reverse!

Code: Select all

health = health - damage;
if (health < minhealth) {health = minhealth};
I have very little coding experience so I don't know if there's a simpler way, but I hope this helps!

Re: EOS: How to keep a value from going over a certain limit?

Posted: Mon May 30, 2022 5:10 am
by ritewriter
I don’t know anything about coding so I just use IF function.

IF Health<0
THEN
Health=0

or in my case

IF willpower>1
THEN
willpower=willpower-1
ELSE
Your willpower can’t get any lower.

Re: EOS: How to keep a value from going over a certain limit?

Posted: Mon May 30, 2022 8:34 am
by Thamrill
If you have to clamp multiple times values between a min and a max, I suggest you implement a basic clamp function in your initial script and then you can call it anywhere in your tease.

In your initial script add:

const clamp = (num, min, max) => Math.min(Math.max(num, min), max);

Then whenever you need to clamp the number between the values you pass it as:

X=clamp(X, minX, maxX);

Where X is your variable and minX and maxX are its limits.

Source: https://www.webtips.dev/webtips/javascr ... javascript

I haven't tried it, but it should work.

~Thamrill

Re: EOS: How to keep a value from going over a certain limit?

Posted: Mon May 30, 2022 12:01 pm
by kerkersklave
EOS does not support const nor lambdas, you'll have to write:

Code: Select all

function clamp(num, min, max) {
  return Math.min(Math.max(num, min), max)
}

Re: EOS: How to keep a value from going over a certain limit?

Posted: Mon May 30, 2022 12:34 pm
by Thamrill
kerkersklave wrote: Mon May 30, 2022 12:01 pm EOS does not support const nor lambdas, you'll have to write:

Code: Select all

function clamp(num, min, max) {
  return Math.min(Math.max(num, min), max)
}
Thanks for pointing that out, I would've gone with a function myself, but I was too lazy to convert it from the source I linked and I didn't know of that EOS limitation.

~Thamrill