Wapted
Wapted

Reputation: 33

How could I do a collision check between two points? (C++)

Essentially, the program I am making will allow the user to import a 3d model (as an fbx or obj). It will then be rendered in the window using openGL, the user will then be able to place points on the model.

So, my problem is, how can I do a collision check between these two points. So if when a straight line is drawn from one point to another, if it hits the 3d model at all, it can return 'true' for example. If it does not pass through the model at all, it will return 'false'.

The image below shows how I will be applying this. (In the image shown below the line trace turns green after it has collided with the model, I just made the image in blender to help describe what I mean.) Example of the use

Upvotes: 2

Views: 444

Answers (1)

user3235832
user3235832

Reputation:

Pseudocode:

function rayhitsmodel(model, pointA, pointB):

    max-distance <- distance-between(pointA, pointB)
    ray-source <- pointA
    ray-direction <- normalize-vector(pointB - pointA)

    for each triangle-index in model.triangle-indices:

        p1 <- model.points[triangle-index.point1]
        ... similarly for p2, p3

        triangle <- p1, p2, p3
        intersection <- intersect-with-triangle(ray-source, ray-direction, triangle)

        if intersection is not nothing
            and distance-between(intersection.point, ray-source) <= max-distance
                return true

    return false

Ray-triangle intersection: https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm.

Can be heavily optimized, e.g. by splitting model into an octree. Intersection becomes O(log n) instead of O(n). See this for ray-octree intersections: Ray - Octree intersection algorithms.

Upvotes: 2

Related Questions