LOG

連結バネ

前回は1つのドットだったが配列にしてみる。
結果

let width    = 600;
let height   = 400;
let mousePos = new PIXI.Point(width / 2,height / 2);
let canvas   = document.getElementById('my-canvas');
let renderer = new PIXI.autoDetectRenderer(
    width,
    height,
    {
        'view'      : canvas,
        'antialias' : true
    }
);
let stage = new PIXI.Container();
renderer.backgroundColor = 0xFFFFFF;

let dotList = [];
let dotNum  = 10;
let distX   = 0;
let distY   = 15;

// =============================================================================
// move event
// =============================================================================
let onMove = (e)=>{
    mousePos.x = e.offsetX;
    mousePos.y = e.offsetY;
}


// =============================================================================
// animation
// =============================================================================
let animate = ()=>{
    requestAnimationFrame(animate);

    let dot;
    let oldDot;
    let tx = null;
    let ty = null;
    for(let i = 0; i<dotNum; i++){
        dot = dotList[i];
        if(i === 0){
            tx = mousePos.x;
            ty = mousePos.y;
        }else{
            oldDot = dotList[i-1];
            tx     = oldDot.x + distX;
            ty     = oldDot.y + distY;
        }

        dot.vx += (tx - dot.x) * dot.spring;
        dot.vy += (ty - dot.y) * dot.spring;
        dot.x += dot.vx *= dot.friction;
        dot.y += dot.vy *= dot.friction;
    }
    renderer.render(stage);
}

// =============================================================================
// init
// =============================================================================
$(()=>{
    let dot;
    for(let i = 0; i<dotNum; i++){
        let dot = new PIXI.Graphics();
        dot.spring   = 0.05;
        dot.friction = 0.8;
        dot.vx       = 0;
        dot.vy       = 0;
        dot.x        = width / 2;
        dot.y        = height / 2;
        dot.beginFill(0x000000);
        dot.drawCircle(0,0,4);
        dot.lineStyle(1,0x000000,1);
        dot.endFill();
        stage.addChild(dot);
        dotList[i]   = dot;
    }
    animate();
    canvas.addEventListener('mousemove',onMove,false);
});