Pure mathematics line segment Vs circle collision detection along with HTML5 example

As a part in a bigger project – which you will hear about soon – I needed to find a quick way to check for collisions between a line segment and a circle. It’s quite an easy task, but man, I found a lot of really weird ways to do it, so here’s my take, based on this Stack Overflow question:
Drag circle center or any of the two segment ends to change and update the result. The algorithm works by first finding the point on the line segment which is the closest to circle’s center. Then we compare the distance with the circle radius. If the distance is smaller than the radius, the circle is colliding with the line segment. Here is the source code:
var game;

var gameOptions = {
    circleRadius: 50
}

window.onload = function() {
    var gameConfig = {
        thpe: Phaser.CANVAS,
        width: 600,
        height: 600,
        scene: [playGame]
    }
    game = new Phaser.Game(gameConfig);
    window.focus()
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    preload(){
        this.load.image("crosshair", "crosshair.png");
    }
    create(){
        this.graphics = this.add.graphics();
        this.circleCenter = this.add.sprite(Phaser.Math.Between(50, game.config.width - 50), Phaser.Math.Between(50, game.config.height - 50), "crosshair");
        this.circleCenter.setInteractive();
        this.segmentStart = this.add.sprite(Phaser.Math.Between(20, game.config.width - 20), Phaser.Math.Between(20, game.config.height - 20), "crosshair");
        this.segmentStart.setInteractive();
        this.segmentEnd = this.add.sprite(Phaser.Math.Between(20, game.config.width - 20), Phaser.Math.Between(20, game.config.height - 20), "crosshair");
        this.segmentEnd.setInteractive();
        this.input.setDraggable([this.circleCenter, this.segmentStart, this.segmentEnd]);
        this.distancePoint = this.add.sprite(0, 0, "crosshair");
        this.text = this.add.text(0, 0, "",{
            fontFamily: "Arial",
            color: "#ffffff"
        });
        this.drawStuff();
        this.input.on("drag", function(pointer, gameObject, dragX, dragY) {
            gameObject.x = dragX;
            gameObject.y = dragY;
            this.drawStuff();
        }, this);
    }
    drawStuff(){
        this.graphics.clear();
        if(this.distToSegmentSquared({
            x: this.circleCenter.x,
            y: this.circleCenter.y
        }, gameOptions.circleRadius, {
            x: this.segmentStart.x,
            y: this.segmentStart.y
        }, {
            x: this.segmentEnd.x,
            y: this.segmentEnd.y
        })){
            this.graphics.lineStyle(2, 0x880000);
        }
        else{
            this.graphics.lineStyle(2, 0x008800);
        }
        this.graphics.strokeCircle(this.circleCenter.x, this.circleCenter.y, gameOptions.circleRadius);
        this.graphics.lineStyle(2, 0x008800);
        this.graphics.beginPath();
        this.graphics.moveTo(this.segmentStart.x, this.segmentStart.y);
        this.graphics.lineTo(this.segmentEnd.x, this.segmentEnd.y);
        this.graphics.closePath();
        this.graphics.strokePath();
        this.graphics.lineStyle(2, 0x888800);
        this.graphics.beginPath();
        this.graphics.moveTo(this.distancePoint.x, this.distancePoint.y);
        this.graphics.lineTo(this.circleCenter.x, this.circleCenter.y);
        this.graphics.closePath();
        this.graphics.strokePath();
        this.text.setText("Segment: (" + this.segmentStart.x + ", " + this.segmentStart.y +") to (" + this.segmentEnd.x + ", " + this.segmentEnd.y +")\nCircle center: (" + this.circleCenter.x + ", " + this.circleCenter.y +")\nPoint to watch: (" + this.distancePoint.x + ", " + this.distancePoint.y +")");
    }
    getDistance(p1, p2){
        return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y);
    }
    distToSegmentSquared(circleCenter, circleRadius, segmentStart, segmentEnd){
        var l2 = this.getDistance(segmentStart, segmentEnd);
        var t = ((circleCenter.x - segmentStart.x) * (segmentEnd.x - segmentStart.x) + (circleCenter.y - segmentStart.y) * (segmentEnd.y - segmentStart.y)) / l2;
        t = Math.max(0, Math.min(1, t));
        var tX = segmentStart.x + t * (segmentEnd.x - segmentStart.x);
        var tY = segmentStart.y + t * (segmentEnd.y - segmentStart.y);
        var tPoint = {
            x: tX,
            y: tY
        }
        this.distancePoint.x = Math.round(tX);
        this.distancePoint.y =  Math.round(tY);
        return this.getDistance(circleCenter, tPoint) < circleRadius * circleRadius;
    }
}
And this is the source code to download. Prepare to see this script in action running in a game this week.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers