How do you configure the points of a ConvexPolygoneShape2D in code?

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

Hello, I’ve only been using Godot for about a week now (so complete beginner) and I have a scene that looks like this:

Node 2D (script attached to it)
– Timer
– Area2D
----CollisionShape2D

(+ other unimportant stuff)

I need the CollisionShape2D to be a ConvexPolygoneShape2D, however you can only set its points in code… I would like to do this in the script attached to the Node2D, but once I got to it I realized there were no tutorials on how to set this up and I’ve tried for several hours without success.

I would like to know how to set the points for the ConvexPolygoneShape2D in code (I am using gdscript), and as a bonus, I would like the points of the ConvexPolygonShape2D to change over time (which is why there is a Timer and the script is attached to the Node2D).

:bust_in_silhouette: Reply From: jgodfrey

Looks like you need to:

  • Create a new ConvexPolygonShape2D
  • Assign points to the new polygon
  • Assign the polygon to your CollisionShape2D object

Here’s an example…

func _ready():
	var collShape = $Area2D/CollisionShape2D
	var polygon = ConvexPolygonShape2D.new()
	var pointArr = PoolVector2Array()
	pointArr.append(Vector2(-32,-32))
	pointArr.append(Vector2(-32, 32))
	pointArr.append(Vector2(32, 32))
	pointArr.append(Vector2(32, -32))
	polygon.points = pointArr
	collShape.shape = polygon

Thank you so much for both the answer and the example! Now it works exactly as I imagined it would.

TheOnlyKnowledge | 2020-05-13 08:01