xxxxxxxxxx
var x1 = 0; // points for line (controlled by mouse)
var y1 = 0;
var x2 = 0; // static point
var y2 = 0;
var sx = 192; // square position
var sy = 545;
var sw = 32; // and size
var sh = 68;
var rects = [];
function setup() {
createCanvas(windowWidth, windowHeight);
for (var i = 0; i < 4; i++){
rects[i] = new Rec(sx+292*i, sy, sw, sh);
}
}
function draw() {
background(255);
lineCheck();
hits();
for (var i = 0; i < rects.length; i++){
rects[i].rect();
}
}
/*for (var i = 0; i < bubbles.length; i++) {
bubbles[i].update();
bubbles[i].display();
for (var j = 0; j < bubbles.length; j++) {
if (i != j && bubbles[i].intersects(bubbles[j])) {
bubbles[i].changeColor();
bubbles[j].changeColor();
*/
function hits(){
var hit = lineRect(x1,y1,x2,y2, sx,sy,sw,sh);
if (hit) fill(255,0, 0);
else fill(0,250, 0);
noStroke();
}
function lineCheck(){
stroke(1);
// set end of line to mouse coordinates
x1 = mouseX;
y1 = mouseY;
line(x1, y1, x2, y2);
//mouse at end of the line
noStroke();
fill(173, 26, 139);
ellipse(mouseX, mouseY, 20, 20);
}
function Rec(x, y, w, h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.rect = function(){
noStroke();
//fill(255, 0, 0);
rect(this.x, this.y, this.w, this.h);
}
}
// LINE/RECTANGLE
function lineRect(x1, y1, x2, y2, rx, ry, rw, rh) {
// check if the line has hit any of the rectangle's sides
// uses the Line/Line function below
var left = lineLine(x1,y1,x2,y2, rx,ry,rx, ry+rh);
var right = lineLine(x1,y1,x2,y2, rx+rw,ry, rx+rw,ry+rh);
var top = lineLine(x1,y1,x2,y2, rx,ry, rx+rw,ry);
var bottom = lineLine(x1,y1,x2,y2, rx,ry+rh, rx+rw,ry+rh);
// if ANY of the above are true, the line
// has hit the rectangle
if (left || right || top || bottom) {
return true;
}
return false;
}
// LINE/LINE
function lineLine(x1, y1, x2, y2, x3, y3, x4, y4) {
// calculate the direction of the lines
var uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
var 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
//var intersectionX = x1 + (uA * (x2-x1));
//var intersectionY = y1 + (uA * (y2-y1));
//fill(255,0,0);
//noStroke();
//ellipse(intersectionX, intersectionY, 20, 20);
return true;
}
return false;
}