Home Game Development collision detection – How to unfold circles evenly round a degree?

collision detection – How to unfold circles evenly round a degree?

0
collision detection – How to unfold circles evenly round a degree?

[ad_1]

Some fast optimizations you may make are to course of collisions in a double-sided approach, so you do not have to course of them twice every, and save your sq. roots for under the circumstances the place you want them:

operate processCollision(c1, c2) {
  const deltaX = c2.x - c1.x;
  const deltaY = c2.y - c1.y;

  const interactionRange = 2;

  // Note in case your circles all have the identical dimension, you may
  // save sumRadius as a relentless externally, and never re-compute it.
  const sumRadius = c1.r + c2.r + interactionRange;
  const squaredDistance = deltaX * deltaX + deltaY * deltaY;
  
  if (squaredDistance === 0 || squaredDistance > sumRadius * sumRadius) { return; } // not colliding

  const centerDistance = Math.sqrt(squaredDistance);
  

  const circleDistance = centerDistance - sumRadius;      

  const power = 5;

  const aX = circleDistance * power * deltaX / centerDistance;
  const aY = circleDistance * power * deltaY / centerDistance; 

  c1.vX += aX;
  c1.vY += aY;

  c2.vX -= aX;
  c2.vY -= aY;
}

Next, preserve some velocity from body to border, and deal with the inward pull as a competing acceleration:

operate replace() {
  ctx.clearRect(0, 0, canvas.width, canvas.top);

  const inertia = 0.8;
  const attraction = 0.1;

  for (const c of circles) {
    c.vX *= inertia;
    c.vY *= inertia;

    c.vX += attraction * ((canvas.width / 2) - c.x);
    c.vY += attraction * ((canvas.top / 2) - c.y);
  }
  
  // Process every spring simply as soon as.
  for (let i = 0; i < circleCount; i++) {
    for (let j = i+1; j < circleCount; j++) {
      processCollision(circles[i], circles[j]);
    }
  }
  
  for (const c of circles) {
    c.x += c.vX * (1 / 60);
    c.y += c.vY * (1 / 60);

    drawCircle(c);
  }
}

Increase the interactionRange parameter to offer extra of a buffer between circles the place the repulsion power can ramp up, and enhance the power parameter to make the ramp steeper, so that you get a stronger push.

If it jerks and jitters an excessive amount of, scale back the inertia parameter to sap extra vitality out of the system.

If the pull into the middle is simply too robust, scale back the attraction parameter. You might even make this attraction ignore distance, so you do not get tighter squeezes on the perimeter than close to the middle.

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here