-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwall_physics.html
More file actions
126 lines (104 loc) · 3.27 KB
/
wall_physics.html
File metadata and controls
126 lines (104 loc) · 3.27 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
<!doctype html>
<html>
<head>
<title>Wall Physics</title>
<script src="vector.js" type="text/javascript"></script>
<script src="models.js" type="text/javascript"></script>
</head>
<body onload="init();">
<table>
<tr valign="top">
<td>
<canvas id="myCanvas" width="500" height="300" style="border:1px solid black;"></canvas><br />
<button onclick="go();">Go</button>
<button onclick="stop();">Stop</button>
<button onclick="animate();">Step</button>
<br />
<input type="text" id="output" />
</td>
<td>
<a href="index.html">Home</a>
<h1>Wall Physics</h1>
<p>New Features</p>
<ul>
<li>Wall objects</li>
<li>Solid surface collision detection and resolution</li>
</ul>
</td>
</tr>
</table>
<script type="text/javascript">
var canvas = null;
var context = null;
var looper = null;
var b = null;
var w = null;
function init()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
b = new ball(50, 50, 10, 1, 20, 0, 'blue');
w = new wall(300, 10, 400, 100);
draw();
go();
}
function draw()
{
b.draw(context);
w.draw(context);
}
function go()
{
looper = setInterval(animate, 30);
}
function animate()
{
update();
checkCollisions();
bounding();
clear();
draw();
}
function clear()
{
context.clearRect(0, 0, canvas.width, canvas.height);
}
function bounding()
{
if (b.p.x <= b.r) { b.p.x = b.r; b.v.x *= -1; }
if (b.p.y <= b.r) { b.p.y = b.r; b.v.y *= -1; }
if (b.p.x >= canvas.width - b.r) { b.p.x = canvas.width - b.r; b.v.x *= -1; }
if (b.p.y >= canvas.height - b.r) { b.p.y = canvas.height - b.r; b.v.y *= -1; }
}
function checkCollisions()
{
if (w.distance(b.p) < b.r)
{
resolveCollision();
}
document.getElementById("output").value = w.distance(b.p);
}
function resolveCollision()
{
// go back just before the collision
b.reset();
// calculate normal and tangent vectors
var vn = w.norm.scale(b.v.dot(w.norm)); // the normal component of the ball's velocity
var vt = b.v.sub(vn); // the tangent component of the ball's velocity
// de-overlap first
var distance = w.distance(b.p);
b.p = b.p.add(b.v.scale((distance - b.r) / vn.mag()));
// calculate new velocity
b.v = vt.sub(vn); // keep the same tangent component and reflect the normal
}
function update()
{
b.move();
}
function stop()
{
clearInterval(looper);
}
</script>
</body>
</html>