Balle rebondissante
Une balle traverse l'écran et rebondit sur les bords. La plus petite boucle qui soit : lire le delta, déplacer, inverser la vitesse.
L'éditeur ci-dessus fait tourner ce projet. Changez une ligne et il se recharge.
Classes Godot utilisées
Polygon2DColorRect
Le code
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