How do you set a shape to a CollisionShape2d when being added as a child?

Godot Version

v4.3

Question

I’m trying to create a simple function that creates walls for a panel that the player can’t move past. So in order to do this I’m creating a function that creates CollisionShape2Ds at some vectors with SegmantShape2D as it’s shape. Then using those vectors as the a and b coordinates in the SegmantShape2D.

but I can’t figure out how to set the shape before making the actual node, I looked to the documentation but couldn’t figure out how to use set_shape here:

var wall = CollisionShape2D.new()

Probably some simple solution to this but I’m pretty new to coding so I got frustrated and couldn’t think of it

If I understand your issue correctly, you are using the position of the CollisionShape2D for the segmentshape2d, but the CollisionShape2d only has a position after being instantiated, but you want to set the position of the SegmentShape2d before that.

If your function is able to position the Collisionshape2d, what I’d do is:

  1. Instantiate the collisionshape2d and position it at point a, which is a Vector2
  2. Create the SegmentShape2D and set the vector a to 0 and b to the end point of the line
  3. call wall.set_shape(mysegmentshape2d)

Now you have your wall at the required positions.

the wall must not be child of player and that should be an independent body.

first , make an area 2d node and make a collision shape for it ; and make it child of wall stutic body.
now , attach a code to wall. and write this:

func ready():
    $CollisionShape.disabled=true

then click on area that you have made; and go to node tab and choose “on_body_entered”.
then choose the wall node.
in created function , remove the pass and comments and write this code instead of them.

func on_area2D_entered(body):
    $CollisionShape.disabled=false

I figured it out, instead of trying to spawn a new child node every frame, I caved and added the collision shapes themselves and then set their position every frame

Feel kind of stupid I didn’t just try this first but oh well. Also this is definitely super inefficient but it works, so I don’t care lol :smile: