RustX/Autonomous_Driving_Simulation
3
1class Sensor{2 constructor(){3 this.rayCount=5;4 this.rayLength=150;5 this.raySpread=Math.PI/4;6 7 this.rays=[];8 this.readings=[];9 }10 11 update(x,y,angle,roadBorders,traffic){12 this.#castRays(x,y,angle);13 this.readings=[];14 for(let i=0;i<this.rays.length;i++){15 this.readings.push(16 this.#getReading(this.rays[i],roadBorders,traffic)17 );18 }19 }20 21 #getReading(ray,roadBorders,traffic){22 let touches=[];23 24 roadBorders.forEach(border => {25 for(let i=1;i<border.length;i++){26 const touch=getIntersection(27 ray[0],28 ray[1],29 border[i-1],30 border[i]31 );32 if(touch){33 touches.push(touch);34 }35 }36 });37 38 for(let i=0;i<traffic.length;i++){39 const poly=traffic[i].polygon;40 for(let j=0;j<poly.length;j++){41 const value=getIntersection(42 ray[0],43 ray[1],44 poly[j],45 poly[(j+1)%poly.length]46 );47 if(value){48 touches.push(value);49 }50 }51 }52 53 if(touches.length==0){54 return null;55 }else{56 const offsets=touches.map(e=>e.offset);57 const minOffset=Math.min(...offsets);58 return touches.find(e=>e.offset==minOffset);59 }60 }61 62 #castRays(x,y,angle){63 this.rays=[];64 for(let i=0;i<this.rayCount;i++){65 const rayAngle=lerp(66 this.raySpread/2,67 -this.raySpread/2,68 this.rayCount==1?0.5:i/(this.rayCount-1)69 )+angle;70 71 const start={x,y};72 const end={73 x:x-Math.sin(rayAngle)*this.rayLength,74 y:y-Math.cos(rayAngle)*this.rayLength75 };76 this.rays.push([start,end]);77 }78 }79 80 draw(ctx){81 for(let i=0;i<this.rayCount;i++){82 let end=this.rays[i][1];83 if(this.readings[i]){84 end=this.readings[i];85 }86 ctx.beginPath();87 ctx.lineWidth=2;88 ctx.strokeStyle="yellow";89 ctx.moveTo(90 this.rays[i][0].x,91 this.rays[i][0].y92 );93 ctx.lineTo(94 end.x,95 end.y96 );97 ctx.stroke();98 /*99 ctx.strokeStyle="black";100 ctx.moveTo(101 this.rays[i][1].x,102 this.rays[i][1].y103 );104 ctx.lineTo(105 end.x,106 end.y107 );108 ctx.stroke();*/109 }110 }111}