# Trying to understand the "Substrate" algorithm

**URL:** https://discourse.processing.org/t/trying-to-understand-the-substrate-algorithm/3031
**Category:** Coding Questions
**Created:** [August 27, 2018, 6:55pm UTC](https://discourse.processing.org/t/trying-to-understand-the-substrate-algorithm/3031 "2018-08-27T18:55:13Z")
**Posts on this page:** 1
**Showing post:** 10

<div class="post-metadata">

### Author: ![jeremydouglass](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/jeremydouglass/32/20_2.png) [@jeremydouglass](https://discourse.processing.org/u/jeremydouglass)
#### Post date: [September 3, 2018, 10:54pm UTC](https://discourse.processing.org/t/trying-to-understand-the-substrate-algorithm/3031/10 "2018-09-03T22:54:19Z")

</div>

Hi @solub.

Here is an example of line-line collision detection – it returns true-false, but you can also return a PVector with the intersection point, which is very useful for truncating a growing line at exactly the right place after it crosses.

```auto
/**
 * Line-Line collision detection
 * http://www.jeffreythompson.org/collision-detection/line-line.php
 */
boolean lineLine(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) {
  // calculate the distance to intersection point
  float uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
  float uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
  // if uA and uB are between 0-1, lines are colliding
  if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
    // optionally, draw a circle where the lines meet
    float intersectionX = x1 + (uA * (x2-x1));
    float intersectionY = y1 + (uA * (y2-y1));
    fill(255, 0, 0);
    noStroke();
    ellipse(intersectionX, intersectionY, 20, 20);
    return true;
  }
  return false;
}

```

---

_[View the full topic](https://discourse.processing.org/t/trying-to-understand-the-substrate-algorithm/3031)._
