Search code examples
math3draymarching

How do I move a point in a specific direction in 3d Space?


I know how to move a point in a direction in 2d space it's like this:

pointX += sin(angle) * movementSpeed;
pointY += cos(angle) * movementSpeed;

but how do I do the same in 3d space assuming the angle variable is replaced with pitch, yaw, and roll variables?

(btw I'm making a ray marching algorithm)


Solution

  • To move a point in 3D space using pitch, yaw, and roll angles, you need to convert these angles into a direction vector. The direction vector describes the direction in which the point will move.

    1. Convert Angles to Radians: Make sure your pitch, yaw, and roll angles are in radians. If they are in degrees, convert them to radians
    2. Compute the Direction Vector: Calculate the direction vector based on pitch and yaw.
    3. Move the Point: Use the direction vector to update the point's position.
    #include <cmath>
    
    // Convert degrees to radians if needed
    constexpr float DEG_TO_RAD = M_PI / 180.0f;
    
    // Function to move a point in 3D space
    void movePointIn3DSpace(float& pointX, float& pointY, float& pointZ, float pitch, float yaw, float movementSpeed) {
        // Convert angles to radians if they are in degrees
        float pitchRad = pitch * DEG_TO_RAD;
        float yawRad = yaw * DEG_TO_RAD;
    
        // Calculate the direction vector
        float dirX = cos(pitchRad) * sin(yawRad);
        float dirY = sin(pitchRad);
        float dirZ = cos(pitchRad) * cos(yawRad);
    
        // Update the point's position
        pointX += dirX * movementSpeed;
        pointY += dirY * movementSpeed;
        pointZ += dirZ * movementSpeed;
    }
    
    // Example usage
    int main() {
        float pointX = 0.0f, pointY = 0.0f, pointZ = 0.0f;
        float pitch = 30.0f;  // degrees
        float yaw = 45.0f;    // degrees
        float movementSpeed = 1.0f;
    
        movePointIn3DSpace(pointX, pointY, pointZ, pitch, yaw, movementSpeed);
    
        // Output the new position
        printf("New position: (%f, %f, %f)\n", pointX, pointY, pointZ);
    
        return 0;
    }
    

    (This is coded in cpp btw)