It will be a different solution for each game, for example, some games will only give, you experience if the enemy is on a similar level. You need to start by giving a hard look to your requirements.
First, we need to start by recognize that the experience gained shall never be negative. Furthermore, I am inferring from your description that when you fight monsters of lower level than you are, it will never result in zero experience, but in increasingly diminishing values instead.
Second, I suspect you want to fix the amount of experience the playing will gain by fighting a monster of the same level.
If we are looking for a function g
, that given a difference of levels x
(monster_level - player_level
) with the description provided, it follows that:
Lim(g(x))_x->-∞ = 0
: When the difference tends to negative infinity, the gained exprience tends to zero
g(0) = k
: When the difference is zero, the gained experience is a constant value k
dg(x)/dx > 0
: The gained experience is a growing function, the greater the difference of levels the greater the gained experience
We cannot represent this with a linear function. To speak is loose terms, a stright line that doesn't cross the origin, and meets the horizontal axis at negative infinity... is an horizontal line. So its slope would be zero. However, we need a slope greater than zero.
It cannot be a quadratic function, because they are not always growing. In fact, you will have a similar problem with higher order functions.
Trigonometric functions are periodic functions, so we can discard those too...
Logarithms are growing on the positive, but decreasing and with an imaginary part on the negative. So, do not base the function on that either...
Exponential functions fit the bill. For example take g(x) = 2^x
:
Lim(2^x)_x->-∞ = 0
2^0 = 1
d/dx {2^x} = log(2) * 2^x > 0
It is very easy to tweak by changing the cosntant 2
to a parameter, but whatever constant we put there, we will get 1
when x = 0
. We could consider to add another term, but that would change the limit when x -> -∞
. Therefore, what we do is mess with the exponent, in particular:
g(x) = k^(x+1)
With this function, you get g(x) = k
when x = 0
. The next thing you will want is to tweak how fast it grows, you can do that by adding a factor to x
:
g(x) = k^(fx+1)
If I want to make sure that g(a) = b
, I do this:
g(x) = k^(fx+1)
g(a) = b
=>
b = k^(fa+1)
=>
log(b) = log(k^(fa+1)
=>
log(b) = (fa+1)*log(k)
=>
log(b)/log(k) = fa+1
=>
log(b)/log(k) - 1 = fa
=>
log(b)/log(k) - 1
------------------ = f
a
I can rewrite the function like this:
g(x) = k^((log(b)/log(k) - 1)*x/a + 1)
=>
g(x) = k*k^((log(b)/log(k) - 1)*x/a)
=>
g(x) = k*(b/k)^(x/a)
It will have the following properties:
Lim(g(x))_x->-∞ = 0
g(0) = k
g(a) = b
dg(x)/dx > 0
Where k
, a
and b
. In addition, remember that x
is monster_level - player_level
.