# How to visualize elastic collision among particles confined in a square 2D container?

I've already simulate two particle confined in a square 2D container, but I don't know how to simulate the elastic collision between them. Currently, they just pass through each other without any collision.

Further, I want to carry this to multiple identical particles system, where many elastic collision will happen.

What's the most effective way to simulate the elastic collision in this multiple identical particles system?

Here's my code.

(*Given two spheres in the square 2D container: initial position and initial velocity*)
ball = {{{0.5, 0.5}, {Cos[\[Pi]/6], Sin[\[Pi]/6]}}, {{0.3, 0.3}, {Cos[1], Sin[1]}}};

Graphics[{PointSize[0.05],
(*Draw the container*)
Line[{{-1, -1}, {1, -1}, {1, 1}, {-1, 1}, {-1, -1}}],
Point[
Dynamic[
(*balls moving*)
ball = Map[{#[[1]] + #[[2]]*0.009, #[[2]]} &, ball];

(*reflection from the container walls*)
ball = Map[If[Abs[#[[1, 2]]] > 1, {{#[[1, 1]], 2*Sign[#[[1, 2]]] - #[[1, 2]]}, {1, -1} #[[2]]}, #] &, ball];
ball = Map[If[Abs[#[[1, 1]]] > 1, {{2*Sign[#[[1, 1]]] - #[[1, 1]], #[[1, 2]]}, {-1, 1} #[[2]]}, #] &, ball];

Map[First, ball]
]]},
PlotRange -> {{-1.025, 1.025}, {-1.025, 1.025}},
ImageSize -> {250, 250}]

• Have a look a the bouncy bubbles question. Dec 2, 2017 at 19:41

Simple fix will be adding this code inside your loop (assuming d is a diameter of your ball):
r = ball[[1, 1]] - ball[[2, 1]];