简体   繁体   中英

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.

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 . 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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