-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
107 lines (92 loc) · 2.3 KB
/
main.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var width, height, canvas, ctx, runner = false;
var ball = {
pos: {
x: 100,
y: 700
},
vel: {
x: 5,
y: -10
},
acc: {
x: 0,
y: 9.81
},
restitution: -0.5,
radius: 25
};
var mouse = {
x: 0, y: 0, isDown: false
};
function setup(){
canvas = document.getElementById("ball"),
ctx = canvas.getContext("2d");
width = window.innerWidth;
height = window.innerHeight;
runner = setInterval(draw, 1000/60);
canvas.width = width;
canvas.height = height;
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
}
function getMousePosition(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
}
function mouseDown(e){
if(e.which == 1){
getMousePosition(e);
mouse.isDown = true;
ball.vel.x = ball.vel.y = 0;
ball.acc.x = ball.acc.y = 0;
ball.radius = 25;
}
}
function mouseUp(e){
if(e.which == 1){
mouse.isDown = false;
ball.vel.y = -1*(ball.pos.y - mouse.y + window.scrollY) / 10;
ball.vel.x = -1*(ball.pos.x - mouse.x + window.scrollX) / 10;
ball.acc.y = 9.81;
}
}
function draw(){
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.arc(ball.pos.x, ball.pos.y, ball.radius, 0, 2*Math.PI, false);
ctx.fillStyle = "red";
ctx.fill();
if(mouse.isDown){
ctx.strokeStyle = "white";
ctx.beginPath()
ctx.moveTo(ball.pos.x, ball.pos.y);
ctx.lineTo(mouse.x-window.scrollX, mouse.y-window.scrollY);
ctx.stroke();
ctx.closePath();
}
update();
}
function update(){
ball.vel.x += ball.acc.x/60;
ball.vel.y += ball.acc.y/60;
ball.pos.x += ball.vel.x*100/60;
ball.pos.y += ball.vel.y*100/60;
if (ball.pos.y > height - ball.radius) {
ball.vel.y *= ball.restitution;
ball.pos.y = height - ball.radius;
}
if (ball.pos.y < ball.radius){
ball.vel.y *= ball.restitution;
ball.pos.y = ball.radius;
}
if (ball.pos.x > width - ball.radius) {
ball.vel.x *= ball.restitution;
ball.pos.x = width - ball.radius;
}
if (ball.pos.x < ball.radius) {
ball.vel.x *= ball.restitution;
ball.pos.x = ball.radius;
}
}
setup();