-
Notifications
You must be signed in to change notification settings - Fork 0
/
boxy.js
93 lines (80 loc) · 2.02 KB
/
boxy.js
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
var rectangleX = 20;
var rectangleY = 20;
var circleX = 50;
var circleY = 300;
var radius = 8;
var previousX = 0;
var previousY = 0;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rec = new Array (10);
//making the bottom left the origin
ctx.translate(0, canvas.height);
ctx.scale(1, -1);
//initial position of the circle
ctx.beginPath();
ctx.arc(circleX,circleY,radius,0,2*Math.PI);
ctx.stroke();
//rectangle class
class Rectangle{
constructor (xcoordinate, ycoordinate, height, width){
this.xcoordinate=xcoordinate;
this.ycoordinate=ycoordinate;
this.height=height;
this.width=width;
}
collision(x,y,r){
if (y+r < this.ycoordinate || y-r > (this.ycoordinate + this.height)
|| (x+r) < this.xcoordinate || (x-r) > (this.xcoordinate + this.width)) {
return false;
}
else {
return true;
}
}
}
//draw rectangles
for (let x = 0; x < 10; x++){
var height = Math.floor((Math.random() *50) + 30);
var width = Math.floor((Math.random()*50)+30);
ctx.fillRect(rectangleX,rectangleY,height,width);
rec[x] = new Rectangle(rectangleX,rectangleY, width, height);
rectangleX += width+30;
rectangleY += height+20;
}
//check collisions
function collisionChecker(){
for (let i =0; i < rec.length; i++){
if(rec[i].collision(circleX,circleY, radius)){
window.alert("COLLISION with rectangle "+i);
return true;
}
}
}
//Recognizing W,A,S,D
document.addEventListener('keydown', function(event) {
previousX = circleX;
previousY = circleY;
if(event.keyCode == 87) {
circleY+= 10;
}
else if(event.keyCode == 83) {
circleY-= 10;
}
else if(event.keyCode == 65){
circleX-= 10;
}
else if(event.keyCode == 68){
circleX+= 10;
}
if (collisionChecker()){
circleX = previousX;
circleY = previousY;
}
else{
ctx.clearRect(previousX-radius-1, previousY-radius-1, radius*2+2, radius*2+2 );
ctx.beginPath();
ctx.arc(circleX,circleY,radius,0,2*Math.PI);
ctx.stroke();
}
});