Created
January 9, 2025 02:09
-
-
Save jonocarroll/8180c068fa46fb3a3be4d7bbf0fd146f to your computer and use it in GitHub Desktop.
Animation of colliding particles based on 'particles' (Chapter 2 of Paul Smaldino’s book, Modeling Social Behavior)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Distances | |
using Plots | |
function ninradius(indiv, radius, distances) | |
findall(distances[indiv, :] .< radius) | |
end | |
function getdists(particlelist) | |
pairwise(Euclidean(), reduce(hcat, [[p.x, p.y] for p in particlelist]), dims=2) | |
end | |
mutable struct Particle | |
x | |
y | |
heading | |
clash | |
end | |
nparticles = 150 | |
particles = [ | |
Particle( | |
rand() * 100, | |
rand() * 100, | |
rand() * 2 * pi, | |
false | |
) for i in 1:nparticles | |
] | |
anim = @gif for iter in 1:400 | |
dists = getdists(particles) | |
for i in 1:nparticles | |
particles[i].clash = false | |
nlist = ninradius(i, 2, dists) | |
if length(nlist) > 1 | |
particles[i].heading = rand() * 2 * pi | |
particles[i].clash = true | |
end | |
end | |
# Update positions | |
for i in 1:nparticles | |
particles[i].x = mod(particles[i].x + cos(particles[i].heading), 100) | |
particles[i].y = mod(particles[i].y + sin(particles[i].heading), 100) | |
end | |
scatter( | |
[particle.x for particle in particles], | |
[particle.y for particle in particles], | |
color=[particle.clash ? :red : :blue for particle in particles], | |
label=false, aspect_ratio=:equal, title="Iter $iter", | |
xlims=(-5, 105), ylims=(-5, 105) | |
) | |
end |
Author
jonocarroll
commented
Jan 9, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment