javascript - 使一个圆重叠时不被另一个圆排斥?

标签 javascript canvas physics collision

我写了一段代码,其中有两个圆圈跟随鼠标。我设法进行了碰撞检测,目前它工作得很好,但我不能让圆圈在不被排斥的情况下保持在一起。

我曾尝试使用一个 bool 值,只要它们重叠就设置为真,然后我检查该 bool 值是否为真,我再次将加速度乘以 -1,但它不起作用,因为它们只会“合并” ”。

我也试过将另一个圆的半径添加到它的位置,但它只是做了一个“传送”。这不是学校作业,这是个人项目:) )

编辑:预期的行为是不被另一个圆圈排斥,而是保持在一起并围绕圆圈移动并前进到鼠标位置而不被排斥。就像在游戏 agar.io 中一样,当您在细胞移动和碰撞时 split 它们时,它们不会排斥,但它们会平滑地围绕彼此移动。

// Setting all up
const canvas = document.getElementById("cv");
const ctx = canvas.getContext("2d");
canvas.width = innerWidth;
canvas.height = innerHeight;

// Math Variables and utilities
const PI = Math.PI;
const TWO_PI = PI * 2;
const HALF_PI = PI / 2;

const random = (n1, n2 = 0) => {
  return Math.random() * (n2 - n1) + n1;
};

const distance = (n1, n2, n3, n4) => {
  let dX = n1 - n3;
  let dY = n2 - n4;
  return Math.sqrt(dX * dX + dY * dY);
};

let circles = []; // Array that stores the two circles
let mouse = {
  x: 0,
  y: 0
}; // mouse object

// Creating the circle class

function Circle(px, py, r, ctx) {
  this.x = px; // X Position
  this.y = py; // Y Position
  this.r = r; // Radius
  this.ctx = ctx; // Canvas context
  this.acc = 0.005; // HardCoded acceleration value

  // Draw circle function
  this.show = function() {
    this.ctx.beginPath();
    this.ctx.fillStyle = "#fff";
    this.ctx.arc(this.x, this.y, this.r, 0, TWO_PI, false);
    this.ctx.fill();
  };

  this.update = function(x, y) {
    // Distance between the mouse's X and Y coords and circle's         // X and Y coords
    let dist = {
      x: x - this.x,
      y: y - this.y
    };

    // Distance formula stated above
    let d = distance(x, y, this.x, this.y);
    if (d > 1) {
      this.x += dist.x * this.acc;
      this.y += dist.y * this.acc;
    }
  };

  // Circle collision
  this.collides = function(other) {
    let d1 = distance(this.x, this.y, other.x, other.y);
    if (d1 <= other.r + this.r) {
      //this.acc *= -1;
      // Do stuff to make the circle that collides to round the other
      // Without getting inside it
    }
  }
}

// Generating the circles
const genCircles = () => {
  // Just generating two circles
  for (let i = 0; i < 2; i++) {
    circles.push(new Circle(random(canvas.width / 2), random(canvas.height / 2), 50, ctx));
  }
};
genCircles();

// Displaying and updating the circles
const showCircles = () => {
  for (let i = 0; i < circles.length; i++) {
    // Mouse Event to update mouse's coords
    canvas.addEventListener("mousemove", (e) => {
      mouse.x = e.x;
      mouse.y = e.y;
    }, true);
    // Iterating over the circles to check for collision
    for (let j = 0; j < circles.length; j++) {
      if (i !== j) {
        circles[i].collides(circles[j])
      }
    }
    // Doing the movement and the display functions
    circles[i].update(mouse.x, mouse.y);
    circles[i].show();
  }
};

// Loop to make it run
const update = () => {
  requestAnimationFrame(update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  showCircles();
};

update();
html body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  display: block;
}
<canvas id="cv"></canvas>

最佳答案

它远非完美,但这是我想出的:您可以根据碰撞的圆圈更新每个圆圈的“中心”xy .对于每个碰撞的圆,xy 成为这些圆的两个中心值之间的中间点。这些值未设置为 this.xthis.y 否则它们会奇怪地跳转。相反,这个新的“相对”xy 仅在确定每次绘制的行进距离时计算和使用。底部的代码片段不能完全正确地工作,因为它最终没有在正确的 x,y 处结束,但可以让您了解它应该做什么。其他任何人都可以随意在我的答案或对我的编辑的基础上进行构建。

// Setting all up
const canvas = document.getElementById("cv");
const ctx = canvas.getContext("2d");
canvas.width = innerWidth;
canvas.height = innerHeight;

// Math Variables and utilities
const PI = Math.PI;
const TWO_PI = PI * 2;
const HALF_PI = PI / 2;

const random = (n1, n2 = 0) => {
  return Math.random() * (n2 - n1) + n1;
};

const distance = (n1, n2, n3, n4) => {
  let dX = n1 - n3;
  let dY = n2 - n4;
  return Math.sqrt(dX * dX + dY * dY);
};

let circles = []; // Array that stores the two circles
let mouse = {
  x: 0,
  y: 0
}; // mouse object

// Creating the circle class

function Circle(px, py, r, ctx) {
  this.x = px; // X Position
  this.y = py; // Y Position
  this.r = r; // Radius
  this.ctx = ctx; // Canvas context
  this.acc = 0.005; // HardCoded acceleration value

  // Draw circle function
  this.show = function() {
    this.ctx.beginPath();
    this.ctx.fillStyle = "#fff";
    this.ctx.arc(this.x, this.y, this.r, 0, TWO_PI, false);
    this.ctx.fill();
  };

  this.update = function(x, y) {
    // Distance between the mouse's X and Y coords and circle's         // X and Y coords
    
    var reletave = {x: this.x, y: this.y};
    
    circles.forEach((cir) => {
      if(cir === this) return;
      if(this.collides(cir))  {
        var floor = {x: Math.floor(cir.x, reletave.x), y: Math.floor(cir.y, reletave.y)};
        var dist = {x: Math.abs(cir.x - reletave.x), y: Math.abs(cir.y - reletave.y)};
        reletave.x = floor.x + dist.x;
        reletave.y = floor.y + dist.y;
      }
    })
    
    let dist = {
      x: x - reletave.x,
      y: y - reletave.y
    };

    // Distance formula stated above
    let d = distance(x, y, reletave.x, reletave.y);
    if (d > 0) {
      this.x += dist.x * this.acc;
      this.y += dist.y * this.acc;
    }
  };

  // Circle collision
  this.collides = function(other) {
    let d1 = distance(this.x, this.y, other.x, other.y);
    return d1 <= other.r + this.r;
  }
}

// Generating the circles
const genCircles = () => {
  // Just generating two circles
  for (let i = 0; i < 2; i++) {
    var collides = true;
    while(collides){
      var circleAdd = new Circle(random(canvas.width / 2), random(canvas.height / 2), 50, ctx);
      collides = false;
      circles.forEach((cir) => {
        collides = circleAdd.collides(cir) ? true : collides;
      });
      if(collides) delete circleAdd;
    }
    circles.push(circleAdd);
  }
};
genCircles();

// Displaying and updating the circles
const showCircles = () => {
  for (let i = 0; i < circles.length; i++) {
    // Mouse Event to update mouse's coords
    canvas.addEventListener("mousemove", (e) => {
      mouse.x = e.x;
      mouse.y = e.y;
    }, true);
    // Iterating over the circles to check for collision
    for (let j = 0; j < circles.length; j++) {
      if (i !== j) {
        if(circles[i].collides(circles[j])) {
          //circles[i].acc = circles[j].acc = 0;
        }
      }
    }
    // Doing the movement and the display functions
    circles[i].update(mouse.x, mouse.y);
    circles[i].show();
  }
};

// Loop to make it run
const update = () => {
  requestAnimationFrame(update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  showCircles();
};

update();
html body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  display: block;
}
<canvas id="cv"></canvas>

关于javascript - 使一个圆重叠时不被另一个圆排斥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48229597/

相关文章:

javascript - 从源代码构建 WysiHat?

javascript - 导航栏在图像上下拉

html5 Canvas : draw together

javascript - 我写了一个 JavaScript 在 Canvas : "ฅ(*ΦωΦ*) ฅ" But the cat jumps weirdly 上移动一只猫

javascript - 将 canvas.focus() 放入 <div> 时防止滚动(仅在 IE 中失败)

java - 开源、纯 Java 物理/动力学库

javascript - 隐藏的 anchor 链接一旦显示就落在下一行

javascript - D3 错误地处理堆积条形图

sprite - 有没有办法直观地看到 Sprite 套件的 SKPhysicsbody 边界?

Swift SceneKit——物理 block 不会相互粘连