2022年10月26日水曜日

2Dでの線と線の交差判定

 線と線の交差判定



<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
<div id="p5canvas"></div>
<script>   

let lp1; //line 1 point 1
let lp2; //line 1 point 2
let lp3; //line 2 point 1
let lp4; //line 2 point 2
let lpm1;//line 3 point 1 mousexy
let lpm2;//line 3 point 2 

function setup() {
	let sqsize=50;
	createCanvas(400, 400).parent("p5canvas");
	textSize(20);
	lp1=createVector(width / 2-sqsize, height / 2-sqsize);
	lp2=createVector(width / 2+sqsize, height / 2+sqsize);
	lp3=createVector(width / 2-sqsize, height / 2+sqsize);
	lp4=createVector(width / 2+sqsize, height / 2-sqsize);
	lpm1=createVector(width / 2-30, height / 2);
	lpm2=createVector(0,0);
}
function mousePressed() {
	lpm1.set(mouseX,mouseY);
}

function crosscheck( p1,p2,p3,p4)
{
  let a1, a2;
  a1 = (p3.x * p2.y - p3.x * p1.y - p1.x * p2.y + p1.x * p1.y - p2.x * p3.y + p2.x * p1.y + p1.x * p3.y - p1.x * p1.y)*
  (p4.x * p2.y - p4.x * p1.y - p1.x * p2.y + p1.x * p1.y - p2.x * p4.y + p2.x * p1.y + p1.x * p4.y - p1.x * p1.y);
  a2 = (p4.x * p1.y - p4.x * p3.y - p3.x * p1.y + p3.x * p3.y - p1.x * p4.y + p1.x * p3.y + p3.x * p4.y - p3.x * p3.y)*
  (p4.x * p2.y - p4.x * p3.y - p3.x * p2.y + p3.x * p3.y - p2.x * p4.y + p2.x * p3.y + p3.x * p4.y - p3.x * p3.y);
  if(a1<=0&&a2<=0)
     return true;
  else
    return false;
}
function draw() {
	background(100);	
		
	strokeWeight(4);
	stroke(155,255,155);
	line(lp1.x,lp1.y,lp2.x,lp2.y); 
	
	stroke(150,255,255);
	line(lp3.x,lp3.y,lp4.x,lp4.y); 
	
	stroke(0,255,100);
	lpm2.set(mouseX,mouseY);
	line(lpm1.x,lpm1.y,lpm2.x,lpm2.y); 
	
	noStroke();
	fill(255);
	text(crosscheck(lpm1,lpm2,lp1,lp2),10,30);
	text(crosscheck(lpm1,lpm2,lp3,lp4),10,60);
}
</script>

0 件のコメント:

コメントを投稿

Arduino IDE が "Downloading index: library_index.tar.bz2" で固まる問題

PCとのシリアル通信が原因の一つらしい '/home/usename/.arduino15/packages' を消すといいらしい ので消すと治った IDEの起動中にフリーズしてたのが治った Downloading index: library_ind...