-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselfDrivingCarSim.html
More file actions
757 lines (637 loc) · 33.4 KB
/
selfDrivingCarSim.html
File metadata and controls
757 lines (637 loc) · 33.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Cars Simulation</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
}
canvas {
display: block;
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
background: rgba(0,0,0,0.5);
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="info">
<h2>Cars Simulation</h2>
<p>Circuit with obstacles and another car</p>
<p>The red car slows down and avoids obstacles</p>
<p id="speedInfo">Current speed: 100%</p>
<p id="obstacleStatus"></p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.7/dat.gui.min.js"></script>
<script>
// Configuration
const config = {
roadWidth: 10,
roadLength: 150, // Circuit shorter
carSpeed: 0.5,
autoSteerStrength: 0.1,
safeDistance: 10, // Safety distance
brakeStrength: 0.8, // Brake force (0-1)
otherCarsCount: 1, // Only one other car
obstacleCount: 5, // Number of obstacles on the road
detectionRange: 15, // Detection range of obstacles
avoidanceStrength: 0.7 // Evasion force (0-1)
};
// Initialization of Three.js
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB); // Blue sky
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 30, 50);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(50, 200, 100);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
scene.add(directionalLight);
// Create the ground
const groundGeometry = new THREE.PlaneGeometry(500, 500);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x228B22, // Dark green
roughness: 0.8,
metalness: 0.2
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
// Define the road path (curve)
const roadCurve = new THREE.CurvePath();
// Create a simpler circuit (oval shape)
const roadHeight = 0.05;
// Define the dimensions of the oval
const ovalWidth = 60;
const ovalHeight = 30;
// Create the points of the oval circuit
const points = [];
const numPoints = 16; // Less points for a simpler circuit
for (let i = 0; i < numPoints; i++) {
const angle = (i / numPoints) * Math.PI * 2;
const x = ovalWidth * Math.cos(angle);
const z = ovalHeight * Math.sin(angle);
points.push(new THREE.Vector3(x, roadHeight, z));
}
// Close the loop by adding the first point to the end
points.push(points[0].clone());
// Create a smooth curve from the points
const curve = new THREE.CatmullRomCurve3(points);
curve.closed = true;
roadCurve.add(curve);
// Create the road geometry
const roadGeometry = new THREE.BufferGeometry();
const roadMaterial = new THREE.MeshStandardMaterial({
color: 0x333333, // Dark gray
roughness: 0.7,
metalness: 0.2
});
// Get points along the curve
const roadPoints = roadCurve.getPoints(500);
// Create the road geometry from the points
const roadShape = new THREE.Shape();
roadShape.moveTo(0, -config.roadWidth / 2);
roadShape.lineTo(0, config.roadWidth / 2);
const extrudeSettings = {
steps: 500,
bevelEnabled: false,
extrudePath: new THREE.CatmullRomCurve3(roadPoints)
};
const roadExtrudeGeometry = new THREE.ExtrudeGeometry(roadShape, extrudeSettings);
const road = new THREE.Mesh(roadExtrudeGeometry, roadMaterial);
road.receiveShadow = true;
scene.add(road);
// Add road markings
const lineMaterial = new THREE.MeshStandardMaterial({ color: 0xFFFFFF });
const lineShape = new THREE.Shape();
lineShape.moveTo(0, -0.2);
lineShape.lineTo(0, 0.2);
const lineExtrudeSettings = {
steps: 500,
bevelEnabled: false,
extrudePath: new THREE.CatmullRomCurve3(roadPoints)
};
const lineGeometry = new THREE.ExtrudeGeometry(lineShape, lineExtrudeSettings);
const line = new THREE.Mesh(lineGeometry, lineMaterial);
line.position.y = 0.05; // Légèrement au-dessus de la route
scene.add(line);
// Create the car
function createCar(color = 0xFF0000) {
const carGroup = new THREE.Group();
// Car body
const carBodyGeometry = new THREE.BoxGeometry(4, 1.5, 2);
const carBodyMaterial = new THREE.MeshStandardMaterial({ color: color });
const carBody = new THREE.Mesh(carBodyGeometry, carBodyMaterial);
carBody.position.y = 1;
carBody.castShadow = true;
carGroup.add(carBody);
// Car cabin
const carTopGeometry = new THREE.BoxGeometry(2, 1, 1.8);
const carTopMaterial = new THREE.MeshStandardMaterial({ color: 0x333333 });
const carTop = new THREE.Mesh(carTopGeometry, carTopMaterial);
carTop.position.set(-0.5, 2, 0);
carTop.castShadow = true;
carGroup.add(carTop);
// Wheels
const wheelGeometry = new THREE.CylinderGeometry(0.5, 0.5, 0.4, 16);
const wheelMaterial = new THREE.MeshStandardMaterial({ color: 0x111111 });
const wheelPositions = [
{ x: 1.5, y: 0.5, z: 1.2 }, // Front right
{ x: 1.5, y: 0.5, z: -1.2 }, // Front left
{ x: -1.5, y: 0.5, z: 1.2 }, // Back right
{ x: -1.5, y: 0.5, z: -1.2 } // Back left
];
wheelPositions.forEach(pos => {
const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
wheel.position.set(pos.x, pos.y, pos.z);
wheel.rotation.z = Math.PI / 2;
wheel.castShadow = true;
carGroup.add(wheel);
});
// Phares
const headlightGeometry = new THREE.SphereGeometry(0.3, 16, 16);
const headlightMaterial = new THREE.MeshStandardMaterial({
color: 0xFFFF00,
emissive: 0xFFFF00,
emissiveIntensity: 0.5
});
const headlightPositions = [
{ x: 2, y: 1, z: 0.8 }, // Droit
{ x: 2, y: 1, z: -0.8 } // Gauche
];
headlightPositions.forEach(pos => {
const headlight = new THREE.Mesh(headlightGeometry, headlightMaterial);
headlight.position.set(pos.x, pos.y, pos.z);
carGroup.add(headlight);
// Add a headlight
const spotLight = new THREE.SpotLight(0xFFFFAA, 0.8);
spotLight.position.set(pos.x, pos.y, pos.z);
spotLight.target.position.set(pos.x + 10, pos.y, pos.z);
spotLight.angle = 0.3;
spotLight.penumbra = 0.2;
spotLight.distance = 30;
spotLight.castShadow = true;
carGroup.add(spotLight);
carGroup.add(spotLight.target);
});
return carGroup;
}
// Fonction pour créer un obstacle
function createObstacle() {
const types = [
{
// Traffic cone
create: () => {
const group = new THREE.Group();
// Base of the cone
const baseGeometry = new THREE.CylinderGeometry(0.7, 1, 0.3, 16);
const baseMaterial = new THREE.MeshStandardMaterial({ color: 0x222222 });
const base = new THREE.Mesh(baseGeometry, baseMaterial);
base.position.y = 0.15;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
// Cone body
const coneGeometry = new THREE.ConeGeometry(0.5, 1.5, 16);
const coneMaterial = new THREE.MeshStandardMaterial({
color: 0xFF5500,
emissive: 0xFF5500,
emissiveIntensity: 0.2
});
const cone = new THREE.Mesh(coneGeometry, coneMaterial);
cone.position.y = 1;
cone.castShadow = true;
group.add(cone);
// Reflective bands
const bandGeometry = new THREE.TorusGeometry(0.4, 0.05, 8, 16);
const bandMaterial = new THREE.MeshStandardMaterial({
color: 0xFFFFFF,
emissive: 0xFFFFFF,
emissiveIntensity: 0.5
});
for (let i = 0; i < 2; i++) {
const band = new THREE.Mesh(bandGeometry, bandMaterial);
band.position.y = 0.7 + i * 0.4;
band.rotation.x = Math.PI / 2;
band.castShadow = true;
group.add(band);
}
return group;
},
scale: 1,
heightOffset: 0
},
{
// Rock
create: () => {
const geometry = new THREE.DodecahedronGeometry(1, 1);
const material = new THREE.MeshStandardMaterial({
color: 0x888888,
roughness: 0.9,
metalness: 0.1
});
const rock = new THREE.Mesh(geometry, material);
rock.castShadow = true;
rock.receiveShadow = true;
// Slightly deform the geometry for a more natural appearance
const positionAttribute = rock.geometry.getAttribute('position');
const positions = positionAttribute.array;
for (let i = 0; i < positions.length; i += 3) {
positions[i] += (Math.random() - 0.5) * 0.2;
positions[i + 1] += (Math.random() - 0.5) * 0.2;
positions[i + 2] += (Math.random() - 0.5) * 0.2;
}
positionAttribute.needsUpdate = true;
return rock;
},
scale: 0.8,
heightOffset: 0.8
},
{
// Baril
create: () => {
const group = new THREE.Group();
// Barrel body
const barrelGeometry = new THREE.CylinderGeometry(0.8, 0.8, 1.5, 16);
const barrelMaterial = new THREE.MeshStandardMaterial({
color: 0xDD2200,
roughness: 0.7
});
const barrel = new THREE.Mesh(barrelGeometry, barrelMaterial);
barrel.position.y = 0.75;
barrel.castShadow = true;
barrel.receiveShadow = true;
group.add(barrel);
// Barrel rings
const ringGeometry = new THREE.TorusGeometry(0.82, 0.06, 8, 16);
const ringMaterial = new THREE.MeshStandardMaterial({ color: 0x333333 });
const ringPositions = [0.25, 0.75, 1.25];
ringPositions.forEach(y => {
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.position.y = y;
ring.rotation.x = Math.PI / 2;
ring.castShadow = true;
group.add(ring);
});
return group;
},
scale: 1,
heightOffset: 0
}
];
// Choose a random obstacle type
const selectedType = types[Math.floor(Math.random() * types.length)];
const obstacle = selectedType.create();
// Apply the scale
obstacle.scale.set(selectedType.scale, selectedType.scale, selectedType.scale);
// Add the height offset
obstacle.position.y += selectedType.heightOffset;
return obstacle;
}
// Create the main car (red)
const mainCar = createCar(0xFF0000);
scene.add(mainCar);
// Create the other cars
const otherCars = [];
// One blue car
const otherCar = createCar(0x3366FF); // Blue
scene.add(otherCar);
// Starting position at half way on the road
otherCars.push({
car: otherCar,
progress: 0.5, // Start at the opposite of our car
baseSpeed: 0.3, // Slower than our car
currentSpeed: 0.3
});
// Create and place the obstacles on the road
const obstacles = [];
for (let i = 0; i < config.obstacleCount; i++) {
// Create a new obstacle
const obstacle = createObstacle();
scene.add(obstacle);
// Choose a random position on the road (but not at the beginning)
const progress = 0.1 + Math.random() * 0.8;
const point = roadCurve.getPoint(progress);
// Slightly vary the position to not be exactly in the middle
const nextPoint = roadCurve.getPoint((progress + 0.01) % 1);
const direction = new THREE.Vector3().subVectors(nextPoint, point).normalize();
// Perpendicular vector to position on the road
const perpVector = new THREE.Vector3(-direction.z, 0, direction.x).normalize();
// Shift the obstacle to the right (our car's lane)
const laneOffset = config.roadWidth / 4;
const offset = laneOffset + (Math.random() * 0.4 - 0.2); // Small random variation
const obstaclePosition = new THREE.Vector3()
.copy(point)
.add(perpVector.multiplyScalar(offset));
obstacle.position.set(obstaclePosition.x, obstacle.position.y, obstaclePosition.z);
// Orient the obstacle towards a random direction
obstacle.rotation.y = Math.random() * Math.PI * 2;
// Add the obstacle to the list
obstacles.push({
object: obstacle,
progress: progress,
position: obstaclePosition
});
}
// Driving variables
let mainCarProgress = 0;
let mainCarPosition = new THREE.Vector3();
let mainCarDirection = new THREE.Vector3();
let mainCarCurrentSpeed = config.carSpeed;
let isAvoidingObstacle = false;
let avoidanceOffset = 0;
let avoidanceDirection = 0;
let detectedObstacle = null;
let obstaclePassedTime = 0; // Time elapsed since we passed the obstacle
const SAFETY_MARGIN = 0.03; // Safety margin to ensure the entire car has passed the obstacle
// Function to calculate the distance between two points on the curve
function distanceBetweenCurvePoints(progress1, progress2) {
// Convert the progressions to actual distance along the curve
let distance = Math.abs(progress1 - progress2);
// Handle the case where the cars are on opposite sides of the looping point (0/1)
if (distance > 0.5) {
distance = 1 - distance;
}
// Convert to an approximation of actual distance (depends on the total length of the road)
return distance * 200; // Arbitrary factor representing the approximate length of the road
}
// Function to check if a car is ahead of the main car
function isCarAhead(mainProgress, otherProgress) {
// Calculate the difference taking into account the looping
let diff = otherProgress - mainProgress;
if (diff < -0.5) diff += 1;
if (diff > 0.5) diff -= 1;
// If the difference is small and positive, the car is ahead
return diff > 0 && diff < 0.5;
}
// Function to detect obstacles on the trajectory
function detectObstacles(carProgress, carDirection, laneOffset) {
// Current position of the car
const carPoint = roadCurve.getPoint(carProgress);
const carPos = new THREE.Vector3().copy(carPoint);
// Perpendicular vector to calculate the position on the lane
const perpVector = new THREE.Vector3(-carDirection.z, 0, carDirection.x).normalize();
const carLanePos = new THREE.Vector3().copy(carPos).add(perpVector.clone().multiplyScalar(laneOffset));
// For each obstacle, check if it is on our trajectory
for (const obstacle of obstacles) {
// Calculate the distance along the curve
const distanceOnCurve = distanceBetweenCurvePoints(carProgress, obstacle.progress);
// If the obstacle is at a detectable distance and ahead of us
if (distanceOnCurve < config.detectionRange && isCarAhead(carProgress, obstacle.progress)) {
// Calculate the lateral distance to the obstacle
const obstaclePos = obstacle.position;
// Calculate the projected position of the car at the obstacle's progress
const projectedPoint = roadCurve.getPoint(obstacle.progress);
const projectedDirection = new THREE.Vector3()
.subVectors(roadCurve.getPoint((obstacle.progress + 0.01) % 1), projectedPoint)
.normalize();
const projectedPerpVector = new THREE.Vector3(-projectedDirection.z, 0, projectedDirection.x).normalize();
const projectedCarPos = new THREE.Vector3()
.copy(projectedPoint)
.add(projectedPerpVector.multiplyScalar(laneOffset + avoidanceOffset));
// Distance between the projected position and the obstacle
const lateralDistance = new THREE.Vector3()
.subVectors(projectedCarPos, obstaclePos)
.length();
// If we are close enough laterally (risk of collision)
if (lateralDistance < 2.5) {
return {
obstacle: obstacle,
distance: distanceOnCurve,
lateralDistance: lateralDistance
};
}
}
}
// No obstacle detected
return null;
}
// Animation function
function animate() {
requestAnimationFrame(animate);
// --- Update the main car ---
// Calculate the speed based on other cars
let targetSpeed = config.carSpeed;
// Check the cars ahead of us
for (const otherCar of otherCars) {
if (isCarAhead(mainCarProgress, otherCar.progress)) {
const distance = distanceBetweenCurvePoints(mainCarProgress, otherCar.progress);
// If a car is too close ahead, slow down
if (distance < config.safeDistance) {
// The closer, the slower
const slowdownFactor = Math.min(distance / config.safeDistance, 1);
const possibleTargetSpeed = otherCar.currentSpeed * slowdownFactor;
// Take the lowest speed among all cars ahead
if (possibleTargetSpeed < targetSpeed) {
targetSpeed = possibleTargetSpeed;
}
}
}
}
// Move the main car along the road
mainCarProgress += mainCarCurrentSpeed / 1000;
if (mainCarProgress > 1) mainCarProgress -= 1;
// Get the current position and direction on the road
const point = roadCurve.getPoint(mainCarProgress);
const nextPoint = roadCurve.getPoint((mainCarProgress + 0.01) % 1);
mainCarPosition.copy(point);
mainCarDirection.subVectors(nextPoint, point).normalize();
// Calculate the base offset for the right lane
const perpVector = new THREE.Vector3(-mainCarDirection.z, 0, mainCarDirection.x).normalize();
const laneOffset = config.roadWidth / 4;
// Detect obstacles on our trajectory
const obstacleInfo = detectObstacles(mainCarProgress, mainCarDirection, laneOffset);
// Obstacle status
const obstacleStatusElement = document.getElementById('obstacleStatus');
// Handle obstacle avoidance
if (!isAvoidingObstacle && obstacleInfo) {
// New obstacle detected, start avoidance
isAvoidingObstacle = true;
// Choose the avoidance direction (left = -1, right = 1)
// For simplicity, we will always avoid to the left (towards the center of the road)
avoidanceDirection = -1;
// Remember the obstacle we are avoiding
detectedObstacle = obstacleInfo.obstacle;
obstaclePassedTime = 0;
if (obstacleStatusElement) {
obstacleStatusElement.textContent = "Obstacle detected! Avoidance maneuver in progress...";
obstacleStatusElement.style.color = "#FF3300";
}
} else if (isAvoidingObstacle) {
if (detectedObstacle) {
// Check if we have passed the obstacle
// We consider the obstacle passed when the car's position has passed the obstacle by a certain safety margin
const carProgress = mainCarProgress;
const obstacleProgress = detectedObstacle.progress;
// Calculate the difference taking into account the looping
let diff = carProgress - obstacleProgress;
if (diff < -0.5) diff += 1;
if (diff > 0.5) diff -= 1;
// The obstacle is passed when the difference is positive and greater than the safety margin
const hasPassedObstacle = diff > SAFETY_MARGIN;
if (hasPassedObstacle) {
// Increase the counter of time since we passed the obstacle
obstaclePassedTime += 1/60; // Approximation of delta time (1/60 second)
// Only start returning to normal trajectory after a certain delay
// to ensure that the entire car (including the rear) has passed the obstacle
if (obstaclePassedTime > 1.0) { // Delay of one second
// Obstacle completely passed, gradually return to normal trajectory
isAvoidingObstacle = false;
detectedObstacle = null;
if (obstacleStatusElement) {
obstacleStatusElement.textContent = "Obstacle avoided. Returning to normal trajectory.";
obstacleStatusElement.style.color = "#33CC33";
// Reset the status after a few seconds
setTimeout(() => {
if (obstacleStatusElement) {
obstacleStatusElement.textContent = "No obstacle detected.";
obstacleStatusElement.style.color = "#FFFFFF";
}
}, 3000);
}
}
}
}
} else {
if (obstacleStatusElement && obstacleStatusElement.textContent === "") {
obstacleStatusElement.textContent = "No obstacle detected.";
obstacleStatusElement.style.color = "#FFFFFF";
}
}
// Update the avoidance offset
if (isAvoidingObstacle) {
// Gradually increase the offset until a maximum value
const maxOffset = config.roadWidth / 3 * avoidanceDirection;
avoidanceOffset += (maxOffset - avoidanceOffset) * 0.1 * config.avoidanceStrength;
} else {
// Gradually return to the normal position
avoidanceOffset *= 0.9;
}
// Apply the offset to stay on the right lane with avoidance
const finalPosition = new THREE.Vector3()
.copy(point)
.add(perpVector.clone().multiplyScalar(laneOffset + avoidanceOffset));
// Position the main car on the road
mainCar.position.set(finalPosition.x, point.y + 1, finalPosition.z);
// Orient the main car in the direction of the road
// Slightly adjust the orientation for the avoidance
const targetAngle = Math.atan2(mainCarDirection.z, mainCarDirection.x);
mainCar.rotation.y = -targetAngle;
// Gradually apply the speed change (progressive acceleration/braking)
if (mainCarCurrentSpeed > targetSpeed) {
// Braking
mainCarCurrentSpeed = Math.max(
targetSpeed,
mainCarCurrentSpeed - config.brakeStrength * 0.01
);
} else {
// Acceleration
mainCarCurrentSpeed = Math.min(
targetSpeed,
mainCarCurrentSpeed + 0.005
);
}
// --- Mise à jour des autres voitures ---
for (const otherCar of otherCars) {
// Move the other cars
otherCar.progress += otherCar.currentSpeed / 1000;
if (otherCar.progress > 1) otherCar.progress -= 1;
// Get position and direction
const otherPoint = roadCurve.getPoint(otherCar.progress);
const otherNextPoint = roadCurve.getPoint((otherCar.progress + 0.01) % 1);
const otherDirection = new THREE.Vector3().subVectors(otherNextPoint, otherPoint).normalize();
// Calculate the position on the right lane
const otherPerpVector = new THREE.Vector3(-otherDirection.z, 0, otherDirection.x).normalize();
// The other cars are also on the right lane
const otherFinalPosition = new THREE.Vector3()
.copy(otherPoint)
.add(otherPerpVector.multiplyScalar(laneOffset));
// Position the other car
otherCar.car.position.set(otherFinalPosition.x, otherPoint.y + 1, otherFinalPosition.z);
// Orient the other car
const otherTargetAngle = Math.atan2(otherDirection.z, otherDirection.x);
otherCar.car.rotation.y = -otherTargetAngle;
}
// Follow the camera with a higher view to see the entire circuit
camera.position.set(
mainCar.position.x - 15 * Math.cos(targetAngle),
50, // Higher for the entire circuit
mainCar.position.z - 15 * Math.sin(targetAngle)
);
camera.lookAt(mainCar.position);
// Add information text on speed and obstacles
const speedInfo = document.getElementById('speedInfo');
if (speedInfo) {
speedInfo.innerHTML = `Current speed: ${(mainCarCurrentSpeed/config.carSpeed*100).toFixed(0)}%`;
// Change the color based on the speed
if (mainCarCurrentSpeed < config.carSpeed * 0.5) {
speedInfo.style.color = '#FF0000'; // Red if we brake hard
} else if (mainCarCurrentSpeed < config.carSpeed * 0.8) {
speedInfo.style.color = '#FFAA00'; // Orange if we slow down a bit
} else {
speedInfo.style.color = '#FFFFFF'; // White otherwise
}
}
// Update the other cars
for (const otherCar of otherCars) {
// Move the other cars
otherCar.progress += otherCar.currentSpeed / 1000;
if (otherCar.progress > 1) otherCar.progress -= 1;
// Get position and direction
const otherPoint = roadCurve.getPoint(otherCar.progress);
const otherNextPoint = roadCurve.getPoint((otherCar.progress + 0.01) % 1);
const otherDirection = new THREE.Vector3().subVectors(otherNextPoint, otherPoint).normalize();
// Calculate the position on the right lane
const otherPerpVector = new THREE.Vector3(-otherDirection.z, 0, otherDirection.x).normalize();
const otherLaneOffset = config.roadWidth / 4; // Same lane as our car
// The other cars are also on the right lane
const otherFinalPosition = new THREE.Vector3()
.copy(otherPoint)
.add(otherPerpVector.multiplyScalar(otherLaneOffset));
// Position the other car
otherCar.car.position.set(otherFinalPosition.x, otherPoint.y + 1, otherFinalPosition.z);
// Orient the other car
const otherTargetAngle = Math.atan2(otherDirection.z, otherDirection.x);
otherCar.car.rotation.y = -otherTargetAngle;
}
renderer.render(scene, camera);
}
// Handle window resizing
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Control interface
const gui = new dat.GUI();
gui.add(config, 'carSpeed', 0.1, 2).name('Max speed');
gui.add(config, 'safeDistance', 5, 30).name('Safety distance');
gui.add(config, 'brakeStrength', 0.1, 1).name('Braking force');
gui.add(config, 'detectionRange', 5, 30).name('Detection range');
gui.add(config, 'avoidanceStrength', 0.1, 1).name('Avoidance force');
// Start the animation
animate();
</script>
</body>
</html>