-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcar.js
More file actions
79 lines (61 loc) · 1.67 KB
/
Copy pathcar.js
File metadata and controls
79 lines (61 loc) · 1.67 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
class Car{
constructor(x,y,width,height){
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.speed = 0;
this.acceleration = 10;
this.maxSpeed=10;
this.friction=0.05;
this.angle=0;
this.sensor= new Sensors(this);
this.controls = new Controls();
}
#move(){
if (this.controls.forward)
this.speed+=this.acceleration
if (this.controls.reverse)
this.speed-=this.acceleration
if (this.speed>this.maxSpeed)
this.speed=this.maxSpeed
if (this.speed<-this.maxSpeed/2)
this.speed= -this.maxSpeed/2
if (this.speed>0)
this.speed-=this.friction
if(Math.abs(this.speed)< this.friction)
this.speed=0
if(this.speed<0)
this.speed+=this.friction;
// angle must account for the rotation of the unit circle
// 90-degrees and counter-clockwise
if(this.speed!=0){
const flip= this.speed?1:-1
if(this.controls.left)
this.angle+=0.03*flip;
if(this.controls.right)
this.angle-=0.03*flip;
this.y-=Math.cos(this.angle)*this.speed;
this.x-=Math.sin(this.angle)*this.speed;
}
}
update(){
this.#move()
this.sensor.update()
}
draw(ctx){
ctx.save()
ctx.translate(this.x,this.y)//translates to the new position
ctx.rotate(-this.angle)
ctx.beginPath();
ctx.rect(
-this.width/2,
-this.height/2,
this.width,
this.height,
)
ctx.fill();
ctx.restore();
this.sensor.draw(ctx)
}
}