Pelota que rebota
Una pelota cruzando la pantalla y rebotando en los bordes. El bucle más pequeño que hay: lee el delta, mueve, invierte la velocidad.
El editor de arriba está ejecutando este proyecto. Cambia una línea y se recarga.
Clases de Godot usadas
Polygon2DColorRect
El 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