Sign in to follow this  
anders211

substract resistance from motion

Recommended Posts

anders211    250

Hi

I have object which gets some initial speed in 3D. So this object has speed in direction X and Z. Constant resistance force acts on this object. This is the only force. So speed is decreased all the time till it reaches 0. And object should move in linear way so relation between Vx and Vz should be constant!

Unfortunately withmy algorithm this relation isn't constant. It changes for one of example from 0.462434 to 0.462439

What might be wrong? Or everything is OK and those are just rounding errors?

 

//Calculate resistance
float res = mUr * ph::g.y * t;
float res_x = 0, res_z = 0;
if(mV.x != 0 && mV.z != 0)
{
        float k = fabs(mV.x/mV.z);
        res_z = res/sqrt(k*k+1); // res = sqrt(res_x*res_x + res_z*res_z)
res_x = k*res_z;
}
else if(!mV.x) {res_z = res;}
else if(!mV.z) {res_x = res;}




if(mV.x != 0)
{
   if(fabs(mV.x) < REST_THRESHOLD_XZ)
   {
mV.x = 0;
#ifdef PHYSIC_DEBUG 
if(mFile) fprintf(mFile, "mVx = 0\n"); 
#endif
}
else if(mGround)// X velocity are reduced because of friction
{
   //mV.x *= (1 - GROUND_FRICTION);
if(mV.x > 0)
{
mV.x += res_x;
   if(mV.x < 0)
mV.x = 0;
}
else
{
mV.x -= res_x;
if(mV.x > 0)
mV.x = 0;
}
#ifdef PHYSIC_DEBUG 
if(mFile) fprintf(mFile, "mVx after friction %f\n", mV.x); 
#endif
}
}


if(mV.z != 0)
{
   if(fabs(mV.z) < REST_THRESHOLD_XZ)
   {
   mV.z = 0;
   #ifdef PHYSIC_DEBUG
   if(mFile) fprintf(mFile, "mVz = 0\n"); 
            #endif
   }
   else if(mGround)// Z velocity are reduced because of friction
   {
            //mV.z *= (1 - GROUND_FRICTION);
if(mV.z > 0)
{
       mV.z += res_z;
                if(mV.z < 0)
mV.z = 0;
}
else
{
       mV.z -= res_z;
if(mV.z > 0)
mV.z = 0;
}
   #ifdef PHYSIC_DEBUG 
   if(mFile) fprintf(mFile, "mVz after friction %f\n", mV.z); 
            #endif
   }
}

 

Share this post


Link to post
Share on other sites
Jan2go    2057
That is a difference of five millionths (5 * 10^-6). It is caused by the floating point precision. You'll most likely never see the difference anywhere but in your debugger (at least for speeds where float is a reasonable representation). If for some reason you need a better precision you can use double instead of float.

Share this post


Link to post
Share on other sites
Waterlimon    4398

You might want to implement a proper vector/position class (assuming its possible) so you dont need to do your math per component.

 

That should make it a lot easier to detect and avoid any issues if there even are any in the first place.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this