# Circle collision

Contact pushes neighbouring discs apart. Move seven type discs of different sizes around a tray.

## Try it

Choose Gather three and watch A, B and C separate. Push A towards C and check that C changes position too.

## Interaction details

Compare centre distance with the sum of the radii. The dragged disc follows the pointer while its neighbours separate along the contact line. Reduced motion shows the gathered result immediately.

## Platform controls

- iOS · Touch a disc and push it into a neighbour. Tap Gather three to repeat a collision.
- Android · Touch a disc and push it into a neighbour. Tap Gather three to repeat a collision.
- PC · Drag a disc, or Tab to it and use the arrows to push it. Reset tray restores the starting positions.

## Where to use it

Make room around a dragged node in an interactive bubble chart or layout.

## Implementation prompt

> Let me drag discs of different sizes. Propagate contact to neighbours, keep every disc inside the tray and resolve overlaps after settling.

## Sources and credits

[D3 · Collide](<https://d3js.org/d3-force/collide>)

## Standalone HTML

Save the code below as an HTML file and open it in your browser. The example works offline.

```html
<!doctype html>
<html lang="en" data-motion-locales="inline">
<head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>활자 원판 정리대 · MotionLab</title><style>
*{box-sizing:border-box} :root{color-scheme:light;font:15px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--ink);background:var(--bg)}body{margin:0;min-height:100svh;display:grid;align-content:center;padding:clamp(10px,2.4vw,25px)}main{width:min(100%,760px);min-width:0;margin:auto}header{display:flex;align-items:baseline;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:9px}h1{margin:0;font-size:clamp(21px,4vw,32px);line-height:1.15;letter-spacing:-.045em}header small,output,.mono{font:650 12px/1.4 ui-monospace,monospace}header small{color:var(--muted)}.board{border:1px solid var(--line);overflow:hidden;border-radius:8px;background:var(--paper)}svg{display:block;width:100%}button{appearance:none;display:inline-flex;justify-content:center;align-items:center;min-height:40px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:5px;padding:5px 12px;font:650 13px/1.2 inherit;font-family:inherit;font-size:13px;font-weight:650;cursor:pointer;touch-action:manipulation}button:focus-visible,input:focus-visible,[tabindex]:focus-visible{outline:3px solid #d96326;outline-offset:2px}button:disabled{opacity:.55;cursor:default}.controls{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin-top:9px}.controls output{margin-inline-start:auto}p{margin:8px 0 0;color:var(--muted);font-size:13px;line-height:1.4;word-break:keep-all;overflow-wrap:anywhere}input[type=range]{accent-color:var(--accent);min-width:65px;cursor:pointer}svg text{font-family:inherit}.drag{touch-action:none;user-select:none;-webkit-user-select:none}.sr-only{position:absolute;clip-path:inset(50%);width:1px;height:1px;overflow:hidden;white-space:nowrap}
:root{--bg:#efe6d9;--paper:#f8eedb;--ink:#42372d;--muted:#615246;--line:#b49d87;--accent:#8c3c28}.board{background:#2c3736;padding:7px}.board svg{max-height:55svh;min-height:170px;border:1px solid #57635c;border-radius:4px;background:#263b3a}.disc{cursor:grab;outline:none;touch-action:none}.disc:active{cursor:grabbing}.disc text{font-family:Georgia,serif;user-select:none;pointer-events:none}.disc .focus{fill:none;stroke:transparent;stroke-width:2;stroke-dasharray:3 4}.disc:focus-visible .focus,.disc[data-selected=true] .focus{stroke:#fff6d4}#group{background:#8e442f;color:#fff6e7;border-color:#8e442f}
</style></head>
<body><main><header><h1 data-text="heading"></h1><small data-text="label"></small></header>
<div class="board"><svg id="tray" class="drag" viewBox="0 0 500 240" role="group" data-label="tray"><defs><pattern id="paper-grid" width="14" height="14" patternUnits="userSpaceOnUse"><circle cx="3" cy="3" r=".8" fill="#71857d"/></pattern></defs><rect width="500" height="240" fill="url(#paper-grid)"/><g id="discs"></g></svg></div>
<div class="controls"><button id="group" data-text="group"></button><button id="reset" data-text="reset"></button><output id="selected"></output></div>
<p data-text="hint"></p></main><script>
'use strict';
const strings={"ko":{"heading":"활자 원판 정리대","label":"충돌 해소","hint":"원판 하나를 다른 원판 사이로 끌어 보세요. ‘세 원 모으기’를 누르면 겹쳐 놓은 세 원이 서로 밀려납니다.","tray":"드래그할 수 있는 활자 원판","group":"세 원 모으기","reset":"처음 배치","picked":"선택","disc":"원판"},"en":{"heading":"Type disc tray","label":"Collision separation","hint":"Drag a disc between its neighbours. Gather three places three overlapping discs in the tray and lets them push apart.","tray":"Draggable type discs","group":"Gather three","reset":"Reset tray","picked":"Selected","disc":"Disc"},"es":{"heading":"Bandeja de tipos","label":"Separación por colisión","hint":"Arrastra un disco entre sus vecinos. Junta tres superpone tres discos y deja que se separen.","tray":"Discos tipográficos móviles","group":"Juntar tres","reset":"Restablecer","picked":"Disco","disc":"Disco"},"zh-Hans":{"heading":"圆形字样盘","label":"碰撞分离","hint":"把圆盘拖到相邻圆盘之间。点击“聚拢三个圆盘”可让三个相叠的圆盘彼此推开。","tray":"可拖动的字样圆盘","group":"聚拢三个圆盘","reset":"还原布局","picked":"已选","disc":"圆盘"}};
const query=new URLSearchParams(location.search);
const lang=query.get('lang')||document.documentElement.lang||'ko';
const t=strings[lang]||strings.ko;
document.documentElement.lang=strings[lang]?lang:'ko';
document.title=t.heading+' · MotionLab';
const $=id=>document.getElementById(id);
for(const el of document.querySelectorAll('[data-text]')) el.textContent=t[el.dataset.text];
for(const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label',t[el.dataset.label]);
const media=matchMedia('(prefers-reduced-motion: reduce)');
const reduced=()=>query.get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')||media.matches;
const NS='http://www.w3.org/2000/svg';
function shape(tag,attrs,parent){const node=document.createElementNS(NS,tag); for(const [k,v] of Object.entries(attrs))node.setAttribute(k,v);parent.append(node);return node;}
function coords(svg,e){const p=new DOMPoint(e.clientX,e.clientY).matrixTransform(svg.getScreenCTM().inverse());return {x:p.x,y:p.y};}
const clamp=(n,min,max)=>Math.min(max,Math.max(min,n));
const tray=$('tray');
const data=[['A',88,92,40,'#f4c77e'],['B',191,72,33,'#dd9067'],['C',275,131,44,'#9bbdaf'],['D',380,74,35,'#d9c585'],['E',412,169,31,'#b9a5bf'],['F',139,178,28,'#c6d2a7'],['G',331,199,26,'#98b5c0']];
let selected=0,drag=null,loop=0,iterations=0;
const discs=data.map(([id,x,y,r,ink],i)=>{
  const el=shape('g',{class:'disc',tabindex:0,role:'button','aria-label':t.disc+' '+id,'data-id':id},$('discs'));
  shape('circle',{r,fill:ink,stroke:'#202f2a','stroke-width':2},el);
  shape('circle',{r:r-5,fill:'none',stroke:'#3a463b','stroke-width':.8,opacity:.65},el);
  shape('path',{d:'M-'+(r*.68)+' '+(r*.30)+'H'+(r*.68),stroke:'#6a5748',opacity:.5},el);
  shape('text',{x:0,y:r*.36,'font-size':r*1.18,fill:'#29382f','text-anchor':'middle'},el).textContent=id;
  shape('circle',{r:r+2.5,class:'focus'},el);
  el.onfocus=()=>choose(i);
  el.onpointerdown=e=>{if(drag||e.button!==0)return;stop();choose(i);const p=coords(tray,e);drag={id:e.pointerId,i,dx:p.x-discs[i].x,dy:p.y-discs[i].y};el.setPointerCapture(e.pointerId);};
  el.onpointermove=e=>{if(drag?.id!==e.pointerId)return;const p=coords(tray,e);place(i,p.x-drag.dx,p.y-drag.dy);};
  el.onpointerup=el.onpointercancel=e=>{if(drag?.id===e.pointerId){drag=null;settle(50);draw();}};
  el.onkeydown=e=>{const direction={ArrowLeft:[-10,0],ArrowRight:[10,0],ArrowUp:[0,-10],ArrowDown:[0,10]}[e.key];
    if(direction){e.preventDefault();stop();place(i,discs[i].x+direction[0],discs[i].y+direction[1]);}
    else if(e.key==='Enter'||e.key===' '){e.preventDefault();choose(i);}};
  return {id,x,y,r,el};
});
function draw(){for(const d of discs){d.el.setAttribute('transform','translate('+d.x+' '+d.y+')');d.el.dataset.x=d.x.toFixed(4);d.el.dataset.y=d.y.toFixed(4);d.el.dataset.radius=d.r;}}
function choose(i){selected=i;for(const [n,d] of discs.entries()) {d.el.dataset.selected=String(n===i);d.el.setAttribute('aria-pressed',String(n===i));}$('selected').textContent=t.picked+' · '+discs[i].id;}
function confine(d){d.x=clamp(d.x,d.r+4,496-d.r);d.y=clamp(d.y,d.r+4,236-d.r);}
function settle(passes,pinned=-1,relax=1){
  for(let step=0;step<passes;step++){
    for(let i=0;i<discs.length;i++){const a=discs[i];for(let j=i+1;j<discs.length;j++){const b=discs[j];
      const dx=b.x-a.x,dy=b.y-a.y,dist=Math.hypot(dx,dy),depth=a.r+b.r-dist;if(depth<=.002)continue;
      const nx=dist?dx/dist:1,ny=dist?dy/dist:0;
      const ma=i===pinned?0:1/(a.r*a.r),mb=j===pinned?0:1/(b.r*b.r);
      const da=depth*relax*ma/(ma+mb),db=depth*relax*mb/(ma+mb);
      a.x-=nx*da;a.y-=ny*da;b.x+=nx*db;b.y+=ny*db;
    }}for(const d of discs)confine(d);
  }
}
function place(i,x,y){const d=discs[i];d.x=x;d.y=y;confine(d);settle(60,i);draw();}
function stop(){cancelAnimationFrame(loop);loop=0;tray.dataset.settled='true';}
function end(){stop();settle(60);draw();}
function frame(){if(reduced()||iterations>=38){end();return;}settle(1,-1,.14);draw();iterations++;loop=requestAnimationFrame(frame);}
$('group').onclick=()=>{stop();[[227,109],[244,99],[241,120]].forEach(([x,y],i)=>Object.assign(discs[i],{x,y}));choose(0);draw();iterations=0;tray.dataset.settled='false';frame();};
$('reset').onclick=()=>{stop();discs.forEach((d,i)=>{d.x=data[i][1];d.y=data[i][2];});choose(0);draw();};
media.addEventListener('change',()=>{if(reduced()&&loop)end();});
new MutationObserver(()=>{if(reduced()&&loop)end();}).observe(document.documentElement,{attributes:true,attributeFilter:['class']});
stop();choose(0);draw();
</script></body></html>
```
