+5 votes

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)
in Engine by (105 points)

2 Answers

+6 votes
Best answer

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)
by (155 points)
selected by

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.

+2 votes

In my project I wrote something like this.

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

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.

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?

Yes, I didn't express myself clearly.

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 webmaster@godotengine.org with your username.