- Home /
Math question
Hi there, I got a problem relacted to math.
In my game, the player is able to kick a ball.
The force of the kick is set by how long he keeps the mouse button pressed down, and the angle of the kick is set by how close the mouse pointer is to the player when he kicks.
Here comes the problem:
If I get the distance from the player to the ball with the function Vector3.Distance(player.position, ball.position), I'll get low numbers when they are close to each other and higher when far.
The kick will have a force 1 when they are near and force 9 when they are far, for example.
So, I need the contrary; 1 when far and 9 when near.
Do you know any solution to this?
Answer by Dragonlance · Oct 04, 2012 at 05:53 PM
Define the max Distancewhere it is still hitting with force 1.
Lets say
int minForce = 1;
int maxForce = 9;
float maxHitDistance = 1.8f;
then get the distance
float distance = Vector3.Distance(player.position, ball.position);
then check the force factor
float factor = (maxHitDistance - distance) / maxHitDistance;
If this is negative, the player is to far away...
If this is positive, you have a linear mapping with this factor from 0.0f to 1.0f. While distance 0.0f is equal 1.0. And if distance = maxHitDistance then it is 0.0f
int force = 0;
if(factor < 0.0f) {
int maxDistanceForceBonus = maxForce - minForce;
force = minForce + Mathf.Round(factor * maxDistanceForceBonus );
}
We did it =) force is not lineary mapped from max distance to zero distance between maxForce and minForce in integer steps.
If you want it float, then change it to float and do not Round.
Have fun!
Thanks for the thumbs! And sorry for the code formatting. This somehow went wrong.
Hooray I make it look nice but I feel one detail is missing.
Linear attenuation goes like this:
var d$$anonymous$$:float=$$anonymous$$value;
var dmax:float=maxValue
var dist = Vector3.Distance(from,to);
var result:float;
if(dist<=d$$anonymous$$)result = 1;
else if (dist>=dmax)result = 0;
else
result = (dmax-dist)/(dmax-d$$anonymous$$);
Yes but i am doing inverse linear attenuation with an offset, mapped to an integer range just like he wanted.
As long as he got what he wants, fine to me. Well now, there are both ways for everyone.
Finally I could test it, but I found a trouble.
Yes, the number grows when the objects are near, but it grows from negative numbers up to 0. When applying the force to the Y axis, the object wont go high, because the force is negative.