簡體   English   中英

如何使用JavaScript確定矩形和旋轉矩形何時相交?

[英]How to determine when rectangle and rotated rectangle intersect using JavaScript?

對於我的應用程序,我有一個用SVG繪制的矩形,它用作命中框,並且我希望制作一個JavaScript函數,該函數會在命中框接觸到圍繞其中心旋轉了某個角度的另一個矩形時返回布爾值true。使用CSS轉換。 我已經從http://www.inkfood.com/collision-detection-with-svg/找到了以下代碼:

function intersectRect(r1, r2) {
var r1 = r1.getBoundingClientRect();    //BOUNDING BOX OF THE FIRST OBJECT
var r2 = r2.getBoundingClientRect();    //BOUNDING BOX OF THE SECOND OBJECT

//CHECK IF THE TWO BOUNDING BOXES OVERLAP
 return !(r2.left > r1.right || 
       r2.right < r1.left || 
       r2.top > r1.bottom ||
       r2.bottom < r1.top);
}

這對於常規矩形非常有用,但是我不確定如何在此基礎上與旋轉的矩形一起使用。 當使用Web瀏覽器中的開發人員工具檢查旋轉的矩形時,可以看到它正確地突出顯示了矩形。 就是說,當我嘗試使用JavaScript提取邊界客戶端矩形時,它將以其未旋轉的形式返回矩形的尺寸。 我的問題是如何為旋轉的矩形接收正確的尺寸,以便可以檢測到它何時與我的Hitbox矩形發生碰撞? 我還有另一種方法可以檢測到我的點擊框何時觸摸旋轉的矩形? 任何幫助將非常感激。 在此處輸入圖片說明

好的,因此在您的用例實際應用之前,這將需要進行大量優化,但是,這確實證明了isPointInPath可以旋轉使用,只要您按點繪制矩形即可(也可以使用fillRectrotate以繪制它,然后僅用lineTo跟蹤輪廓,但不stroke以創建要檢查的邊界框。

要測試isPointInPath ,請編輯checkXcheckY的值

 var ctx = document.querySelector('canvas').getContext('2d') function rotate(x, y, a, b, degrees){ let angle = degrees * (Math.PI / 180), sinA = Math.sin(angle), cosA = Math.cos(angle) return [ cosA * (a - x) - sinA * (b - y) + x, sinA * (a - x) + cosA * (b - y) + y ] } function drawRect(x, y, w, h, rotation){ var manipFn = rotation ? rotate : function(a,b){ return [a,b]; } var coords = { bottomLeft: manipFn(x,y,x,y,rotation), bottomRight: manipFn(x,y,x+w,y,rotation), topRight: manipFn(x,y,x+w,y+h,rotation), topLeft: manipFn(x,y,x,y+h,rotation) } var checkX = 106, checkY = 18 ctx.moveTo(...coords.bottomLeft) ctx.strokeStyle = "#3a1" ctx.lineWidth = 1 ctx.lineTo(...coords.bottomRight) ctx.lineTo(...coords.topRight) ctx.lineTo(...coords.topLeft) ctx.lineTo(...coords.bottomLeft) console.log(ctx.isPointInPath(checkX,checkY)) ctx.stroke() ctx.closePath() ctx.fillStyle = "#000" ctx.fillRect(checkX, checkY, 2, 2) } //drawRect(10, 10, 20, 30) drawRect(100, 10, 20, 30, 45) 
 canvas { width: 500px; height: 500px; border: 1px solid black; } 
 <canvas></canvas> 

SVG規范中有很多缺點,但這是您要求的有效示例。 警告,這是陷阱!!

https://codepen.io/josephscottstevens/pen/XEgbrP

window.onmousemove = function(e) {
  var c = document.getElementById("circle");
  var l = document.getElementById("line");
  var displayDiv = document.getElementById("isColiding");
  var circle = { radius : c.r, center : { x:c.cx, y:c.cy } };
  var line =   { p1 : { x:l.x1, y:l.y1 }, p2 : { x:l.x2, y:l.y2 } };
  displayDiv.textContent = circle.radius; //(distance == 0) ? "coliding" : "not coliding";
  moveSection("circle", e.clientX - 20, e.clientY - 20);
  var distance = circleDistFromLineSeg(circle, line);


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM