+1 vote

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?

asked Jan 16, 2019 in Engine by Atkinson (13 points)

1 Answer

+1 vote

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
# Since the drawn line is angled, we have to adjust the CollisionShape's angle too

# Create the StaticBody2D
var static_body = StaticBody2D.new()
# Add the CollisionShape we've created as child of the StaticBody
# 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
# Add the StaticBody as a child of the StaticBody

This creates a StaticBody2D covering the line.

answered Jan 16, 2019 by Tornadowarnung (16 points)

Thank you very much.

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 How to use this Q&A? before posting your first questions.