How to resize a collisionpolygon2d?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By psear

I asked a similar question some time ago to no avail, but how do I resize a CollisionPolygon2d? I’ve heard you can’t use scale, and I don’t actually want to. I’m doubling the size of all my sprites (outside of godot, the new imported textures are doubled) and I want to just resize all of the collision bodies.

Is there a way to double every element in the PoolVector2Array or something like that? Any built in function or plugin?

:bust_in_silhouette: Reply From: vnmk8

each polygon shape has a coordinate for each point, you can see them on the inspector, just change the position of the points to make the polygon bigger or smaller you can see them by selecting the polygon shape and clicking on the text that says PoolVector2Array on the inspector

I know of this option, I was hoping for something automated. I have about 40 collision shapes and each shape has about 50 points.

psear | 2020-11-18 20:05

:bust_in_silhouette: Reply From: Deozaan

I found your question because I wanted to dynamically scale my CollisionPolygon2D at runtime. After being disappointed that there was no “easy” solution I could find, I thought about it for a while and realized that resizing a CollisionPolygon2D via script is a relatively simple process under the following conditions:

  • You want to uniformly scale each vertex.
  • The scale is relative to the origin (0,0) of the polygon.

Here’s what I came up with:

# how much to scale each vertex by
var scaleAmount : float = 2
# reference to the PoolVector2Array on the CollisionPolygon2D
var polygon : PoolVector2Array = $CollisionPolygon2D.polygon

# scale each vertex
for i in polygon.size():
    polygon.set(i, polygon[i] * scaleAmount)

# assign the newly scaled vertices to the CollisionPolygon2D
$CollisionPolygon2D.polygon = polygon

I’m inexperienced with Godot and GDScript, so there are probably better ways to do it. Nonetheless, the above code could probably be modified to work as an editor tool.