Reuben Levine
Reuben Levine

Reputation: 11

How can I change the position of the points in a Polygon2D node with a line of code?

There doesn't seem to be any clear info elsewhere online on this topic. What I want to do is write a line of code to specify the location of a specific point in the polygon. How is this done?

I tried this:

var newPoly = Polygon2D.new()
newPoly.polygon = [[0,0],[100,100],[400,500]]

But it has no effect on the polygon node itself.

Upvotes: 1

Views: 1027

Answers (1)

Theraot
Theraot

Reputation: 40315

The polygon property is a PackedVector2Array, that is a compact in memory array of Vector2D.

While Godot will try to convert any Array to PackedVector2Array when you assign it, Godot will not covert Array to Vector2D.

Thus, instead of this:

newPoly.polygon = [[0,0],[100,100],[400,500]]

You need to do this:

newPoly.polygon = [Vector2(0,0),Vector2(100,100),Vector2(400,500)]

By the way, there Godot is converting from int to float, you can write float literals if you want (e.g. 0.0 instead of 0). And if you want to be explicit about the conversion to PackedVector2Array, you can pass the array to PackedVector2Array(...). For example:

newPoly.polygon = PackedVector2Array(
    [
        Vector2(0.0, 0.0),
        Vector2(100.0, 100.0),
        Vector2(400.0, 500.0)
    ]
)

Upvotes: 3

Related Questions