From 8c20d255acf05100018c7e0ba96fc6e217265561 Mon Sep 17 00:00:00 2001 From: KHALED MOHAMED FATHALLAH MOHAMED Date: Sun, 10 Dec 2023 14:24:17 +0200 Subject: [PATCH] MAKE CAR SENSORS --- main_project/car.js | 5 +++- main_project/self_driving_car.html | 1 + main_project/sensor.js | 38 ++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/main_project/car.js b/main_project/car.js index aefb452..998a764 100644 --- a/main_project/car.js +++ b/main_project/car.js @@ -18,12 +18,14 @@ class Car{ this.friction=0.05; this.angel=0; - this.controls=new Controls(); + this.sensor = new Sensors(this); + this.controls = new Controls(); } //Update the screen with the moving car object update(){ this.#move(); + this.sensor.update(); } //Move method conation the car move by keys logic @@ -92,5 +94,6 @@ class Car{ ctx.fill(); ctx.restore(); + this.sensor.draw(ctx); } } \ No newline at end of file diff --git a/main_project/self_driving_car.html b/main_project/self_driving_car.html index 4bb3bbd..1637bc6 100644 --- a/main_project/self_driving_car.html +++ b/main_project/self_driving_car.html @@ -8,6 +8,7 @@ + diff --git a/main_project/sensor.js b/main_project/sensor.js index ea9d4cb..1b27d3c 100644 --- a/main_project/sensor.js +++ b/main_project/sensor.js @@ -9,6 +9,44 @@ class Sensors{ this.car = car; this.rayCount=3; this.rayLength=100; + this.raySpread=Math.PI/4; + + this.rays=[]; } + + + update(){ + this.rays == []; + for(let i = 0; i < this.rayCount; i++){ + const rayAngle = lerp( + this.raySpread / 2, + -this.raySpread / 2, + i/(this.rayCount - 1) + ); + + const start = {x:this.car.x, y:this.car.y}; + const end = { + x:this.car.x - Math.cos(rayAngle) * this.rayLength, + y: this.car.y = Math.cos(rayAngle) * this.rayLength + }; + this.rays.push([start, end]); + } + } + draw(ctx){ + for (let i = 0; i < array.rayCount; i++) { + ctx.beginPath(); + ctx.lineWidth = 2; + ctx.strokeStyle = "yellow"; + ctx.moveTo( + this.rays[i][0].x, + this.rays[i][0].y + ); + ctx.lineTo( + this.rays[i][1].x, + this.rays[i][1].y + ); + ctx.stroke(); + } + } } \ No newline at end of file