Bola quicando

Uma bola atravessando a tela e quicando nas bordas. O menor loop que existe: lê o delta, move, inverte a velocidade.

O editor acima está rodando este projeto. Mude uma linha e ele recarrega.

Classes do Godot usadas

Polygon2DColorRect

O código

scripts/main.gd
extends Node

const RADIUS: float = 30.0
const SEGMENTS: int = 32

var ball: Polygon2D
var velocity: Vector2 = Vector2(360, 280)


func _ready() -> void:
	_add_background()

	ball = _make_circle(RADIUS, Color('#8da5f3'))
	ball.position = get_viewport().get_visible_rect().size * 0.5
	add_child(ball)


func _process(delta: float) -> void:
	var bounds: Vector2 = get_viewport().get_visible_rect().size
	var limit: Vector2 = Vector2(RADIUS, RADIUS)

	ball.position += velocity * delta

	if ball.position.x < limit.x or ball.position.x > bounds.x - limit.x:
		velocity.x = -velocity.x

	if ball.position.y < limit.y or ball.position.y > bounds.y - limit.y:
		velocity.y = -velocity.y

	ball.position = ball.position.clamp(limit, bounds - limit)


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)


func _make_circle(radius: float, color: Color) -> Polygon2D:
	var points: PackedVector2Array = PackedVector2Array()

	for i in SEGMENTS:
		var angle: float = TAU * i / SEGMENTS
		points.append(Vector2(cos(angle), sin(angle)) * radius)

	var circle: Polygon2D = Polygon2D.new()
	circle.polygon = points
	circle.color = color

	return circle

Mais exemplos de Movimento