Line-Line intersection for y=mx+c

I was wondering how to make a function that you give it two line equations in the form y=mx+c

you pass it the gradient and y-intercept of both.

then it returns a vector which is the point in which the two given lines would intersect

Check out Daniel Shiffman’s “Ray Tracing” on youtube. He explains it quite well

class Line {

  //PVector a,b;
  float x1, x2, y1, y2;
  PVector m;
  cell a, b;
  
  Line(float a, Float b,float c, Float d) {
    x1 = a;
    y1 = b;

    x2 = c;
    y2 = d;
    
  };
  Line(int a, int b,int c, int d) {
    x1 = a;
    y1 = b;

    x2 = c;
    y2 = d;
    
  };
  
  Line(PVector cell1, PVector cell2) {
    x1 = cell1.x;
    y1 = cell1.y;

    x2 = cell2.x;
    y2 = cell2.y;
    
  };
  
  Line(PVector cell1, PVector cell2,PVector c) {
    
    x1 = cell1.x;
    y1 = cell1.y;

    x2 = cell2.x;
    y2 = cell2.y;
    m = new PVector(c.x,c.y);
  };
  Line(cell cell1, cell cell2) {
    x1 = cell1.x;
    y1 = cell1.y;

    x2 = cell2.x;
    y2 = cell2.y;
  };

  void checkMouse() {
  };
  
  void draw(){
    stroke(0);
    strokeWeight(2);
    line(x1,y1,x2,y2);
  };
  
  void drawM(){
    stroke(0);
    strokeWeight(20);
    point(m.x,m.y);
  };
};

PVector checkIntersect(Line a, Line b) {

  float a1 = a.y2 - a.y1;
  float b1 = a.x1 - a.x2;
  float c1 = a1 * a.x1 + b1 * a.y1;
  float a2 = b.y2 - b.y1;
  float b2 = b.x1 - b.x2;
  float c2 = a2 * b.x1 + b2 * b.y1;
  float denom = a1 * b2 - a2 * b1;
  //stroke(0,0,255);
  //strokeWeight(2);
  //line(a.x1,a.y1,a.x2,a.y2);
  //stroke(0,255,255);
  //strokeWeight(2);
  //line(b.x1,b.y1,b.x2,b.y2);
  if ((a.x1==b.x1||a.x2==b.x2)&&(a.y1==b.y1||a.y2==b.y2)) {
    
    return null;
  } else {

    Float X = (b2 *c1 - b1 * c2) / denom;
    Float Y = (a1 *c2 - a2 * c1) / denom;
    
    PVector p = new PVector(X, Y);   
    boolean Linea = ((p.x<a.x1&&p.x>a.x2)||(p.x>a.x1&&p.x<a.x2))&&((p.y<a.y1&&p.y>a.y2)||(p.y>a.y1&&p.y<a.y2));
    boolean Lineb = ((p.x<b.x1&&p.x>b.x2)||(p.x>b.x1&&p.x<b.x2))&&((p.y<b.y1&&p.y>b.y2)||(p.y>b.y1&&p.y<b.y2));
    float n = 0.001;
    if (Linea&&Lineb) {
      //strokeWeight(10);
      //stroke(255,255,0);
      //point(p.x,p.y);
      //strokeWeight(1);
      return p;
    } else {
      return null;
    }
  }
};

Hello,

“Wonder is the beginning of wisdom.” - Socrates

You can adapt this easily into a function:

A simple example of returning a PVector:

PVector v1;

void setup() 
  {
  size(500, 500);
  background(0);
  }

void draw()
  { 
  v1 = dot(mouseX, mouseY);
  println(v1);
  
  strokeWeight(2);
  stroke(255, 255, 0);
  point(v1.x, v1.y);  
  }

PVector dot(float x, float y) 
  {
  PVector v = new PVector(x, y);
  return v;
  }

:)