-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchallenge-160.3.html
More file actions
97 lines (85 loc) · 3.01 KB
/
challenge-160.3.html
File metadata and controls
97 lines (85 loc) · 3.01 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
<html>
<head>
<title>Challenge #160 - Spring Forces</title>
<script src="https://cdn.jsdelivr.net/npm/p5@1.5.0/lib/p5.min.js"></script>
<script>
const RestLength = 200;
const K = 0.01;
let bob;
let anchor;
let spring;
let gravity;
class Spring {
constructor(k, restLength, begin, end) {
this.K = k;
this.restLength = restLength;
this.begin = begin;
this.end = end;
}
update() {
let force = p5.Vector.sub(this.end.position, this.begin.position);
let displacement = force.mag() - this.restLength;
force.normalize().mult(this.K * displacement);
this.begin.applyForce(force);
force.mult(-1);
this.end.applyForce(force);
}
show() {
strokeWeight(4);
stroke(255);
line(
this.begin.position.x,
this.begin.position.y,
this.end.position.x,
this.end.position.y
);
}
}
class Particle {
constructor (x, y) {
this.acceleration = createVector(0, 0);
this.velocity = createVector(0, 0);
this.position = createVector(x, y);
this.mass = 1;
}
applyForce(force) {
let f = force.copy();
f.div(this.mass);
this.acceleration.add(f);
}
update() {
this.velocity.mult(0.99);
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
show() {
stroke(255);
strokeWeight(2);
fill(45, 197, 244);
ellipse(this.position.x, this.position.y, 64);
}
}
function setup() {
createCanvas(800, 600);
bob = new Particle(350, 300);
anchor = new Particle(300, 0);
gravity = createVector(0, 0.2);
spring = new Spring(K, RestLength, bob, anchor);
}
function draw() {
background(112, 50, 126);
spring.show();
spring.update();
bob.show();
bob.update();
anchor.show();
anchor.update();
if (mouseIsPressed) {
bob.position.set(mouseX, mouseY);
bob.velocity.set(0, 0);
}
}
</script>
</head>
</html>