Monday 29 December 2014

(SOLVED) Can You Find the Bug?

I'll leave this here for posterity...

The problem was not with the Vector method, but with the caller. I was casting the angle of roundAngle() to int instead of using the math::round function. D'oh!


This is supposed to constrict the vector to 45 degree slots. Only 2D, ignore the z component. The (rounding?) bug occurs when the correct answer is 180 and -90; this algorithm returns 179 and -89 respectively. Why?!

    // ----------------------------------------------------
    //   round the angle to nearest x degrees
    // ----------------------------------------------------
    Vector3 Vector3::roundAngle ( int nearest_angle )
    {
            // vector to return
            Vector3 rounded;

            // convert to radians
            double nearest_radians = RADIANS ( nearest_angle );

            // get the angle of this vector
            double angle =  atan2 ( this->y, this->x );

            // remainder between 2 angles
            double remainder = std::fmod ( angle, nearest_radians );

            // if there is a remainder, do the rounding
            if ( remainder != 0 ) {

                    double new_angle = round ( angle / nearest_radians ) * nearest_radians;

                    rounded.x = cos ( new_angle );
                    rounded.y = sin ( new_angle );
            }else{
                    rounded.x = this->x;
                    rounded.y = this->y;
                    rounded.z = this->z;
            }

            if ( fabs ( rounded.x ) < TOL ) rounded.x = 0;
            if ( fabs ( rounded.y ) < TOL ) rounded.y = 0;
            if ( fabs ( rounded.z ) < TOL ) rounded.z = 0;

            return rounded.normalised();
    }

No comments:

Post a Comment