Conveyor belt
Two belts that never move a pixel. constant_linear_velocity drags whatever is touching them.
The editor above is running this project. Change a line and it reloads.
Godot classes used
StaticBody2DRigidBody2DCollisionShape2D
The code
scripts/main.gd
extends Node
const BELT_SIZE: Vector2 = Vector2(520, 34)
const BOX_SIZE: Vector2 = Vector2(46, 46)
func _ready() -> void:
_add_background()
var view: Vector2 = get_viewport().get_visible_rect().size
_add_belt(Vector2(view.x * 0.35, view.y * 0.4), 260.0)
_add_belt(Vector2(view.x * 0.65, view.y * 0.65), -260.0)
_add_wall(Vector2(view.x * 0.5, view.y - 30), Vector2(view.x, 60))
_spawn_loop(view)
print('the belts never move, constant_linear_velocity drags whatever touches them')
func _spawn_loop(view: Vector2) -> void:
while is_inside_tree():
_add_box(Vector2(view.x * 0.2, view.y * 0.2))
await get_tree().create_timer(1.1).timeout
func _add_belt(center: Vector2, speed: float) -> void:
var shape: RectangleShape2D = RectangleShape2D.new()
shape.size = BELT_SIZE
var collision: CollisionShape2D = CollisionShape2D.new()
collision.shape = shape
var belt: StaticBody2D = StaticBody2D.new()
belt.position = center
belt.constant_linear_velocity = Vector2(speed, 0)
belt.add_child(_make_rect(BELT_SIZE, Color('#8da5f3')))
belt.add_child(collision)
add_child(belt)
var arrow: Label = Label.new()
arrow.text = '>>>' if speed > 0 else '<<<'
arrow.position = center + Vector2(-24, -46)
arrow.add_theme_color_override('font_color', Color('#999999'))
add_child(arrow)
func _add_wall(center: Vector2, size: Vector2) -> void:
var shape: RectangleShape2D = RectangleShape2D.new()
shape.size = size
var collision: CollisionShape2D = CollisionShape2D.new()
collision.shape = shape
var wall: StaticBody2D = StaticBody2D.new()
wall.position = center
wall.add_child(_make_rect(size, Color('#2a2f3d')))
wall.add_child(collision)
add_child(wall)
func _add_box(at: Vector2) -> void:
var shape: RectangleShape2D = RectangleShape2D.new()
shape.size = BOX_SIZE
var collision: CollisionShape2D = CollisionShape2D.new()
collision.shape = shape
var box: RigidBody2D = RigidBody2D.new()
box.position = at
box.add_child(_make_rect(BOX_SIZE, Color.from_hsv(randf(), 0.4, 0.9)))
box.add_child(collision)
add_child(box)
await get_tree().create_timer(9.0).timeout
if is_instance_valid(box):
box.queue_free()
func _make_rect(size: Vector2, color: Color) -> Polygon2D:
var rect: Polygon2D = Polygon2D.new()
rect.polygon = PackedVector2Array([-size * 0.5, Vector2(size.x, -size.y) * 0.5, size * 0.5, Vector2(-size.x, size.y) * 0.5])
rect.color = color
return rect
func _add_background() -> void:
var background: ColorRect = ColorRect.new()
background.color = Color('#12141a')
add_child(background)
background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)