简体   繁体   English

检查圆与路径(画布)之间的碰撞

[英]checking for collision between circle and path (canvas)

I need to see if part of a circle touches a certain path. 我需要查看圆的一部分是否触及某个路径。 The path also has a width of 20. Currently, I'm creating a circle with a radius of 20 every 4 pixels of the path and checking if any of these circles touch the other circles but this is a performance nightmare and I'm sure there is a better way to do this. 该路径的宽度也为20。目前,我正在创建一个半径为每4像素半径为20的圆,并检查这些圆是否与其他圆接触,但这是一场性能噩梦,我敢肯定有更好的方法可以做到这一点。

I'm not using your numbers because you don't post any code. 我没有使用您的电话号码,因为您没有发布任何代码。 In order to detect collision between 2 circles you need to check if the distance between the 2 circles is <= R + r + lineWidth . 为了检测2个圆之间的碰撞,您需要检查2个圆之间的距离是否<= R + r + lineWidth In this case I'm using a very wide semitransparent stroke, because in this way you may see how the stroke lays over the circle: half inside and half outside. 在这种情况下,我使用的是非常宽的半透明笔触,因为这样一来,您可能会看到该笔触是如何放置在圆上的:内部一半,外部一半。

 const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let cw = canvas.width = 300; let ch = canvas.height = 300; let c = {} cx = cw / 2; cy = ch / 2; let R = 50; let r = 20; let lineWidth = 30; let m = {x:-100,y:-100} ctx.fillStyle = "#d9d9d9"; ctx.strokeStyle = "rgba(255,0,0,.5)" ctx.lineWidth = 30; // main circle drawCircle(cx,cy,R); canvas.addEventListener("mousemove",(evt)=>{ ctx.clearRect(0,0,cw,ch) m = oMousePos(canvas, evt); drawCircle(cx,cy,R); drawCircle(mx,my,r); if(dist(c, m) <= R + r + lineWidth){output.innerHTML = "collision"}else{output.innerHTML = ""} }); function drawCircle(cx,cy,r){ ctx.beginPath(); ctx.arc(cx,cy,r,0,2*Math.PI); ctx.fill(); ctx.stroke(); } function dist(p1, p2) { let dx = p2.x - p1.x; let dy = p2.y - p1.y; return Math.sqrt(dx * dx + dy * dy); } function oMousePos(canvas, evt) { var ClientRect = canvas.getBoundingClientRect(); return { //objeto x: Math.round(evt.clientX - ClientRect.left), y: Math.round(evt.clientY - ClientRect.top) } } 
 canvas { border:1px solid #d9d9d9; margin:0 auto; } p{min-height:1.5em;} 
 <p id="output"></p> <canvas id="canvas"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM