/
index.js
91 lines (78 loc) · 1.86 KB
/
index.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
let host;
let shared;
function preload() {
partyConnect("wss://demoserver.p5party.org", "ball_drop");
shared = partyLoadShared("shared");
host = partyLoadShared("host");
}
function setup() {
createCanvas(400, 400);
noStroke();
// set initial values
if (partyIsHost()) {
host.ball = {
x: width * 0.5,
y: 0,
dX: 0,
dY: 0,
};
shared.click = {
x: width * 0.51,
y: height * 0.5,
};
}
}
function draw() {
background("#660066");
noStroke();
if (partyIsHost()) {
fill(255);
textSize(20);
textFont("Courier New");
text("Hosting!", 10, 30);
}
// read shared data
if (partyIsHost()) {
// apply momentum
host.ball.x += host.ball.dX;
host.ball.y += host.ball.dY;
// apply gravity
host.ball.dY += 0.6;
// respawn
if (host.ball.y > height + 50) {
host.ball = {
x: width * 0.5,
y: -50,
dX: 0,
dY: 0,
};
}
// handle collisions
if (dist(host.ball.x, host.ball.y, shared.click.x, shared.click.y) < 40) {
// move out of penetration
const collision_vector = createVector(
host.ball.x - shared.click.x,
host.ball.y - shared.click.y
);
collision_vector.normalize();
host.ball.x = shared.click.x + collision_vector.x * 40;
host.ball.y = shared.click.y + collision_vector.y * 40;
// bounce
const velocityVector = createVector(host.ball.dX, host.ball.dY);
velocityVector.reflect(collision_vector);
velocityVector.mult(0.5);
host.ball.dX = velocityVector.x;
host.ball.dY = velocityVector.y;
}
}
// draw
fill("white");
ellipse(host.ball.x, host.ball.y, 40, 40);
fill("#66ff66");
ellipse(shared.click.x, shared.click.y, 40, 40);
}
function mousePressed(e) {
// write shared data
shared.click.x = mouseX;
shared.click.y = mouseY;
}