0 votes

I have 2 polygons, which are made with PoolVector2Arrays.

var PolygonA = PoolVector2Array(a,b,c,d)
var PolygonB = PoolVector2Array(x,y,z)

Now I want to get the intersection points of the two Polygons. (Look at the picture)


I would be very pleased, if somebody could give me an idea how I can get these points.

in Engine by (371 points)
edited by

1 Answer

+1 vote
Best answer

You can use the inbuilt https://docs.godotengine.org/de/stable/classes/class_geometry.html#class-geometry-method-segment-intersects-segment-2d function to calculate the intersections like this:

onready var PolA = $P1.polygon
onready var PolB = $P2.polygon

func _ready():
    print (get_intersections())

func get_intersections() -> PoolVector2Array:
    var g = Geometry
    var result: PoolVector2Array

    var p11: Vector2 
    var p12: Vector2
    var p21: Vector2
    var p22: Vector2

    # nested loops checking intersections 
    # between all segments of both polygons
    for i in range(0, PolA.size()):
        p11 = PolA[i]
        p12 = PolA[i + 1] if i + 1 < PolA.size() else PolA[0]
        for j in range(0, PolB.size()):
            p21 = PolB[j]
            p22 = PolB[j + 1] if j + 1 < PolB.size() else PolB[0]
            # use Geometry function to evaluate intersections
            var intersect = g.segment_intersects_segment_2d(p11, p12, p21, p22)
            if intersect != null: result.append(intersect)
    return result
by (1,750 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.