Two elements crossing each other

Hey guys,

so I’ve faced a very simple issue but I cant get over it. I got a rect and a line crossing each other. I need the coordinate where they are crossing each other. How can I get this point?

See me example below:

1 Like

A classic example of asking a question without showing us any code. This is how much code I had to write to even START solving the problem:

float rx, ry, rw, rh, x1, y1, x2, y2;

void setup(){
  size(440,440);
  stroke(255);
  noFill();
}

void draw(){
  background(0);
  
  rx = random(width/2);
  ry = random(height/2);
  rw = random(width/2);
  rh = random(height/2);
  
  x1 = random(rx, rx+rw);
  y1 = random(ry, ry+rh);
  
  x2 = random(width);
  while( rx <= x2 && x2 <= rx+rw){
    x2 = random(width);
  }
  
  y2 = random(height);
  while( ry <= y2 && y2 <= ry + rh ){
    y2 = random(height);
  }  
  
  rect(rx,ry,rw,rh);
  line(x1,y1,x2,y2);
  
  noLoop();
}

void keyPressed(){
  loop();
}

Anyway, the idea is that you know the rectangle is made up of four lines itself, so you just check each of those lines to see if it crosses the single line.

Line-Line intersection is a solved problem; you can easily search the internet for a solution.

2 Likes

Here is a demonstration of solving line-line intersection in Processing:

Note that a rectangle is made up of four lines, and that your line might cross any one of them – or more than one. It is even (in theory) possible for the line and one side of the rect to be on top of one another.