aboutsummaryrefslogtreecommitdiff
path: root/test-client/particles.ts
blob: ba695cc04ea49caafd465a6cf412d93cd015703c (plain)
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
import { ctx } from "./main.ts";
import { V2 } from "./util.ts";

const particles = new Set<Particle>()
let particles_to_remove = new Set<Particle>()

export function tick_particles(dt: number) {
    particles.forEach(p => p.tick(dt) ? {} : particles_to_remove.add(p))
    particles_to_remove.forEach(p => particles.delete(p))
    particles_to_remove = new Set()
}
export function draw_particles() {
    particles.forEach(p => p.draw())
}
export function particle_count() { return particles.size }

export function particle_splash(pos: V2) {
    for (let i = 0; i < 64; i++) {
        const p = new Particle()
        p.px = pos.x + 0.5
        p.py = pos.y + 0.5
        const a = Math.random() * Math.PI * 2
        const r = Math.sqrt(Math.random()) * 5.
        p.vx = Math.sin(a) * r
        p.vy = Math.cos(a) * r
        p.decay = 4.
        p.tr = Math.sqrt(Math.random()) * 1.
        p.c = `hsl(${Math.random() * 0.2 + 0.7}turn, 100%, 50%)`
        p.r = Math.random() * 0.1 + 0.03
        particles.add(p)
    }
}

class Particle {
    c = "red"
    r = 0.05
    tr = 0
    px = 0
    py = 0
    vx = 0
    vy = 0
    decay = 1

    tick(dt: number) {
        this.tr -= dt
        this.px += this.vx * dt;
        this.py += this.vy * dt;
        this.vx *= Math.exp(-dt * this.decay)
        this.vy *= Math.exp(-dt * this.decay)
        return this.tr > 0.
    }
    draw() {
        ctx.fillStyle = this.c
        ctx.globalAlpha = Math.min(1, this.tr * 5.)
        ctx.beginPath()
        ctx.arc(this.px, this.py, this.r, 0, Math.PI * 2)
        ctx.fill()
    }
}