Search code examples
c++openglglm-math

Create Vector B Using Position and Direction of Vector A


I am currently trying to understand how to go about creating a vector at a specific position relative to the position and direction of another vector. For example, I have this illustration which might help explain what I am trying to accomplish:

enter image description here

Point A contains properties: glm::vec3 position and glm::vec3 direction. Now let's say I want point B to be 2 units in front of A. Is there a way to solve this mathematically using glm to determine the position of B?


Solution

  • A point on a ray can be get by:

    B = A + D * t
    

    where A is the origin of the ray, D is a the direction vector with length 1 (Unit vector) and t is the distance form A to B.

    With the GLM this can be expressed like this:

    struct Ray
    {
        glm::vec3 position;
        glm::vec3 direction;
    };
    
    Ray A;
    
    float t = 2.0f;
    glm::vec3 B = A.position + glm::normalize(A.direction) * t;
    

    normalize() calculates a vector in the same direction as the given vector, but with length of 1.

    If the direction vector is stored as a unit vector (with length 1), then the expensive normalize() operation can be avoided, when a point on the ray is calculated.
    I recommend to define a class Ray which can calculate a point on the ray:

    class Ray
    {
    public:
    
       Ray(const glm::vec3 &O, const glm::vec3 &D)
         : _O(O)
         , _D(glm::normalize(D))
       {}
    
       glm::vec3 P(float t) const {
           return _O + _D * t;
       }
    
    private:
        glm::vec3 _O;
        glm::vec3 _D;
    };
    
    Ray A(glm::vec3(....), glm::vec3(....));
    
    glm::vec3 B = A.P( 2.0f );