Adding StaticBody2D to the object with a script

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

Hi
Sorry if this question has been asked before, but I could not find it.
I have a line created with the script:

func _draw():
     draw_line(Vector2(0,0), Vector2(50, 50), Color(255, 0, 0), 1)

How to add StaticBody 2D physics to this object with a script?

:bust_in_silhouette: Reply From: Tornadowarnung

The line itself isn’t really an object in the scene as far as I understand. What you want to do is to create a StaticBody2D that just so happens to have the same position and properties as the drawn line.

There are actually two ways to add a CollisionShape2D in script. However, I will only cover the option in which you add the CollisionShape2D as a child of the StaticBody2D since I never fully understood the shape_owner API (you can read more on that in the CollisionObject2D docs).

func _draw():
# These variables representing the line's attributes help to better understand which values are used in the code below
var start_point = Vector2(0,0)
var end_point = Vector2(50, 50)
var line_width = 1
# Draw the line
draw_line(start_point, end_point, Color(255, 0, 0), line_width)

# Create a new Shape
var shape = RectangleShape2D.new()
# Use half of the drawn line's length as x because the extent represents half of the shape's actual width
var shape_width = Vector2(0, 0).distance_to(end_point) / 2
# Use half of the drawn line's width as y for the same reason as above
var shape_height = line_width * 0.5
# That way the shape represents the drawn line's geometry
shape.set_extents(Vector2(shape_width, shape_height))

# Create a new collisionShape
var collision_shape = CollisionShape2D.new()
# Add the shape we created before to this collision shape
collision_shape.set_shape(shape)
# Since the drawn line is angled, we have to adjust the CollisionShape's angle too
collision_shape.set_rotation(start_point.angle_to_point(end_point))

# Create the StaticBody2D
var static_body = StaticBody2D.new()
# Add the CollisionShape we've created as child of the StaticBody
static_body.add_child(collision_shape)
# Use the drawn line's middle as the position of our StaticBody
var static_body_position = (end_point - start_point) / 2
# Set the StaticBody's position to the middle of the drawn line
static_body.set_position(static_body_position)
# Add the StaticBody as a child of the StaticBody
add_child(static_body)

This creates a StaticBody2D covering the line.

Thank you very much.

Atkinson | 2019-01-17 08:54