Move your pointer to move the yellow circle.

0:01 / 0:30
Playback speed

Circle collider

Bring the circles together slowly. Watch where the two coloured radius lines meet.

Interactive demo#Collision

A round collision shape, tested by comparing distance with radius.

Two circles touch when the distance between their centres is less than their radii added together. It’s one line of maths, and it’s the natural fit for balls, bullets and explosions.

Code

src/demos/circle_collider.goose
namespace circle_collider_lesson;
import stage;
import std;
import math;

export "circle-collider" fn draw(time: f64, dt: f64, px: f64, py: f64, hover: bool) {
    artwork("draft");
    let dx = px - 62;
    let dy = py - 50;
    let distance = hypot(dx, dy);
    let hit = distance < 21 + 13;
    let divisor = if distance == 0 { 1.0 } else { distance };
    let ux = dx / divisor;
    let uy = dy / divisor;
    draw_prop("compass", 41, 29, 42, 42);
    draw_prop("marble", px - 13, py - 13, 26, 26);
    ell(62, 50, 21, 21, if hit { "rgba(255,43,214,.35)" } else { "rgba(111,168,255,.3)" });
    ell(px, py, 13, 13, if hit { "rgba(255,43,214,.35)" } else { "rgba(255,212,71,.3)" });
    ring(62, 50, 21, SKY);
    ring(px, py, 13, SUN);
    line(62, 50, px, py, LINE, 2, 2);
    line(62, 50, 62 + ux * 21, 50 + uy * 21, if hit { MAG } else { SKY });
    line(px, py, px - ux * 13, py - uy * 13, if hit { MAG } else { SUN });
    rect(61, 49, 3, 3, WHITE);
    rect(px - 1, py - 1, 3, 3, WHITE);
}

Stage drawing helpers · All demos on GitHub

Comments

No comments yet.