Reflection velocity

Posted by MindSeeker on Game Development See other posts from Game Development or by MindSeeker
Published on 2014-06-05T03:50:06Z Indexed on 2014/06/05 9:45 UTC
Read the original article Hit count: 228

I'm trying to get a moving circular object to bounce (elastically) off of an immovable circular object. Am I doing this right? (The results look right, but I hate to trust that alone, and I can't find a tutorial that tackles this problem and includes the nitty gritty math/code to verify what I'm doing). If it is right, is there a better/faster/more elegant way to do this?

Note that the object (this) is the moving circle, and the EntPointer object is the immovable circle.

        //take vector separating the two centers <x, y>, and then get unit vector of the result:
        MathVector2d unitnormal = MathVector2d(this -> Retxpos() - EntPointer -> Retxpos(), this -> Retypos() - EntPointer -> Retypos()).UnitVector();

         //take tangent <-y, x> of the unitnormal:
        MathVector2d unittangent = MathVector2d(-unitnormal.ycomp, unitnormal.xcomp);

        MathVector2d V1 = MathVector2d(this -> Retxvel(), this -> Retyvel());

        //Calculate the normal and tangent vector lengths of the velocity: (the normal changes, the tangent stays the same)
        double LengthNormal = DotProduct(unitnormal, V1);
        double LengthTangent = DotProduct(unittangent, V1);

        MathVector2d VelVecNewNormal = unitnormal.ScalarMultiplication(-LengthNormal); //the negative of what it was before

        MathVector2d VelVecNewTangent = unittangent.ScalarMultiplication(LengthTangent); //this stays the same

        MathVector2d NewVel = VectorAddition(VelVecNewNormal, VelVecNewTangent); //combine them

        xvel = NewVel.xcomp; //and then apply them
        yvel = NewVel.ycomp;

Note also that this question is just about velocity, the position code is handled elsewhere (in other words, assume that this code is implemented at the exact moment that the circles begin to overlap).

Thanks in advance for your help and time!

© Game Development or respective owner

Related posts about physics

Related posts about 2d-physics