How to create a collision shape from code?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By al.glez
:warning: Old Version Published before Godot 3 was released.

I’m trying to create a collision shape from code, but with no luck so far.

var shape = RectangleShape2D.new()
var collision = CollisionShape2D.new()
shape.set_extents(Vector2(70,70))
collision.set_shape(shape)
:bust_in_silhouette: Reply From: DriNeo

In my project I wrote something like this.

 var shape = RectangleShape2D.new()
 get_node("StaticBody2D").add_shape(shape)
 shape.set_extents(Vector2(70,70))

If i’m not wrong, that is no exactly the same, as you already has a StaticBody2D node and you are just adding a shape. I want to create a collision shape directly from Area2D node, and not from a CollisionShape2D node.

al.glez | 2016-03-05 16:35

When you say:

I want to create a collision shape directly from Area2D node

you meant that your script is attached to a Area2D node?

kocholes | 2016-03-07 12:46

Yes, I didn’t express myself clearly.

al.glez | 2016-03-07 14:02

:bust_in_silhouette: Reply From: kocholes

If your script is attached to an Area2D node, then you can try something like this:

var shape = RectangleShape2D.new()
shape.set_extents(Vector2(70,70))
	
var collision = CollisionShape2D.new()
collision.set_shape(shape)
	
add_child(collision)

Hi Sorry, but I didn’t have time to answer before. I tested today that solution and is working, but I’m not sure why only within _process(), I will test further anyway.

al.glez | 2016-03-29 21:59