根据质量和弹跳系数计算球与球碰撞的速度和方向

时间:2012-02-24 02:18:18

标签: javascript html5 canvas physics

我使用了基于this

的以下代码
ballA.vx = (u1x * (m1 - m2) + 2 * m2 * u2x) / (m1 + m2);
ballA.vy = (u1y * (m1 - m2) + 2 * m2 * u2y) / (m1 + m2);

ballB.vx = (u2x * (m2 - m1) + 2 * m1 * u1x) / (m1 + m2);
ballB.vy = (u2y * (m2 - m1) + 2 * m1 * u1y) / (m1 + m2);

但显然效果并不好,因为公式是针对一维碰撞而设计的。

所以我尝试使用this section中的以下公式。

但问题是我不知道偏转角是什么以及如何计算它。另外,如何考虑这个公式中的弹跳系数?

修改:我可能还不清楚。上面的代码 可以工作,虽然它可能不是预期的行为,因为原始公式是针对一维碰撞而设计的。因此,我正在尝试的问题是:

  • 什么是 2D 等效?
  • 如何考虑弹跳系数
  • 如何计算方向(用 v x v y <表示< / em>)碰撞后的两个球?

3 个答案:

答案 0 :(得分:11)

我应该首先说:我创造了一个新的答案,因为我觉得旧的答案很简单

这里承诺的是一个更复杂的物理引擎,但我仍然觉得它很容易跟随(希望!或者我只是浪费了我的时间......哈哈),(网址:http://jsbin.com/otipiv/edit#javascript,live

function Vector(x, y) {
  this.x = x;
  this.y = y;
}

Vector.prototype.dot = function (v) {
  return this.x * v.x + this.y * v.y;
};

Vector.prototype.length = function() {
  return Math.sqrt(this.x * this.x + this.y * this.y);
};

Vector.prototype.normalize = function() {
  var s = 1 / this.length();
  this.x *= s;
  this.y *= s;
  return this;
};

Vector.prototype.multiply = function(s) {
  return new Vector(this.x * s, this.y * s);
};

Vector.prototype.tx = function(v) {
  this.x += v.x;
  this.y += v.y;
  return this;
};

function BallObject(elasticity, vx, vy) {
  this.v = new Vector(vx || 0, vy || 0); // velocity: m/s^2
  this.m = 10; // mass: kg
  this.r = 15; // radius of obj
  this.p = new Vector(0, 0); // position  
  this.cr = elasticity; // elasticity
}

BallObject.prototype.draw = function(ctx) {
  ctx.beginPath();
  ctx.arc(this.p.x, this.p.y, this.r, 0, 2 * Math.PI);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
};

BallObject.prototype.update = function(g, dt, ppm) {

  this.v.y += g * dt;
  this.p.x += this.v.x * dt * ppm;
  this.p.y += this.v.y * dt * ppm;

};

BallObject.prototype.collide = function(obj) {

  var dt, mT, v1, v2, cr, sm,
      dn = new Vector(this.p.x - obj.p.x, this.p.y - obj.p.y),
      sr = this.r + obj.r, // sum of radii
      dx = dn.length(); // pre-normalized magnitude

  if (dx > sr) {
    return; // no collision
  }

  // sum the masses, normalize the collision vector and get its tangential
  sm = this.m + obj.m;
  dn.normalize();
  dt = new Vector(dn.y, -dn.x);

  // avoid double collisions by "un-deforming" balls (larger mass == less tx)
  // this is susceptible to rounding errors, "jiggle" behavior and anti-gravity
  // suspension of the object get into a strange state
  mT = dn.multiply(this.r + obj.r - dx);
  this.p.tx(mT.multiply(obj.m / sm));
  obj.p.tx(mT.multiply(-this.m / sm));

  // this interaction is strange, as the CR describes more than just
  // the ball's bounce properties, it describes the level of conservation
  // observed in a collision and to be "true" needs to describe, rigidity, 
  // elasticity, level of energy lost to deformation or adhesion, and crazy
  // values (such as cr > 1 or cr < 0) for stange edge cases obviously not
  // handled here (see: http://en.wikipedia.org/wiki/Coefficient_of_restitution)
  // for now assume the ball with the least amount of elasticity describes the
  // collision as a whole:
  cr = Math.min(this.cr, obj.cr);

  // cache the magnitude of the applicable component of the relevant velocity
  v1 = dn.multiply(this.v.dot(dn)).length();
  v2 = dn.multiply(obj.v.dot(dn)).length(); 

  // maintain the unapplicatble component of the relevant velocity
  // then apply the formula for inelastic collisions
  this.v = dt.multiply(this.v.dot(dt));
  this.v.tx(dn.multiply((cr * obj.m * (v2 - v1) + this.m * v1 + obj.m * v2) / sm));

  // do this once for each object, since we are assuming collide will be called 
  // only once per "frame" and its also more effiecient for calculation cacheing 
  // purposes
  obj.v = dt.multiply(obj.v.dot(dt));
  obj.v.tx(dn.multiply((cr * this.m * (v1 - v2) + obj.m * v2 + this.m * v1) / sm));
};

function FloorObject(floor) {
  var py;

  this.v = new Vector(0, 0);
  this.m = 5.9722 * Math.pow(10, 24);
  this.r = 10000000;
  this.p = new Vector(0, py = this.r + floor);
  this.update = function() {
      this.v.x = 0;
      this.v.y = 0;
      this.p.x = 0;
      this.p.y = py;
  };
  // custom to minimize unnecessary filling:
  this.draw = function(ctx) {
    var c = ctx.canvas, s = ctx.scale;
    ctx.fillRect(c.width / -2 / s, floor, ctx.canvas.width / s, (ctx.canvas.height / s) - floor);
  };
}

FloorObject.prototype = new BallObject(1);

function createCanvasWithControls(objs) {
  var addBall = function() { objs.unshift(new BallObject(els.value / 100, (Math.random() * 10) - 5, -20)); },
      d = document,
      c = d.createElement('canvas'),
      b = d.createElement('button'),
      els = d.createElement('input'),
      clr = d.createElement('input'),
      cnt = d.createElement('input'),
      clrl = d.createElement('label'),
      cntl = d.createElement('label');

  b.innerHTML = 'add ball with elasticity: <span>0.70</span>';
  b.onclick = addBall;

  els.type = 'range';
  els.min = 0;
  els.max = 100;
  els.step = 1;
  els.value = 70;
  els.style.display = 'block';
  els.onchange = function() { 
    b.getElementsByTagName('span')[0].innerHTML = (this.value / 100).toFixed(2);
  };

  clr.type = cnt.type = 'checkbox';
  clr.checked = cnt.checked = true;
  clrl.style.display = cntl.style.display = 'block';

  clrl.appendChild(clr);
  clrl.appendChild(d.createTextNode('clear each frame'));

  cntl.appendChild(cnt);
  cntl.appendChild(d.createTextNode('continuous shower!'));

  c.style.border = 'solid 1px #3369ff';
  c.style.display = 'block';
  c.width = 700;
  c.height = 550;
  c.shouldClear = function() { return clr.checked; };

  d.body.appendChild(c);
  d.body.appendChild(els);
  d.body.appendChild(b);
  d.body.appendChild(clrl);
  d.body.appendChild(cntl);

  setInterval(function() {
    if (cnt.checked) {
       addBall();
    }
  }, 333);

  return c;
}

// start:
var objs = [],
    c = createCanvasWithControls(objs),
    ctx = c.getContext('2d'),
    fps = 30, // target frames per second
    ppm = 20, // pixels per meter
    g = 9.8, // m/s^2 - acceleration due to gravity
    t = new Date().getTime();

// add the floor:
objs.push(new FloorObject(c.height - 10));

// as expando so its accessible in draw [this overides .scale(x,y)]
ctx.scale = 0.5; 
ctx.fillStyle = 'rgb(100,200,255)';
ctx.strokeStyle = 'rgb(33,69,233)';
ctx.transform(ctx.scale, 0, 0, ctx.scale, c.width / 2, c.height / 2);

setInterval(function() {

  var i, j,
      nw = c.width / ctx.scale,
      nh = c.height / ctx.scale,
      nt = new Date().getTime(),
      dt = (nt - t) / 1000;

  if (c.shouldClear()) {
    ctx.clearRect(nw / -2, nh / -2, nw, nh);
  }

  for (i = 0; i < objs.length; i++) {

    // if a ball > viewport width away from center remove it
    while (objs[i].p.x < -nw || objs[i].p.x > nw) { 
      objs.splice(i, 1);
    }

    objs[i].update(g, dt, ppm, objs, i);

    for (j = i + 1; j < objs.length; j++) {
      objs[j].collide(objs[i]);
    }

    objs[i].draw(ctx);
  }

  t = nt;

}, 1000 / fps);

真正的“肉”和讨论的起源是obj.collide(obj)方法。

如果我们潜入(我这次评论它,因为它比“最后一个”复杂得多),你会看到这个等式:equation for inelastic collision,仍然是这一行中唯一使用的等式:this.v.tx(dn.multiply((cr * obj.m * (v2 - v1) + this.m * v1 + obj.m * v2) / sm));现在我确定你还在说:“zomg wtf!这是一个相同的单维方程式!”但当你停下来想想它只是一次“碰撞”发生在一个维度。这就是为什么我们使用矢量方程来提取适用的分量并将碰撞仅应用于那些特定的部分而使其他部分不受影响地继续它们的快乐方式(忽略摩擦并简化碰撞以不考虑动态能量转换力,如评论CR)。随着对象复杂度的增加和场景数据点的数量增加,这个概念显然变得更加复杂,以解决诸如畸形,转动惯量,不均匀的质量分布和摩擦点等问题......但这远远超出了它的范围,它几乎不会值得一提..

基本上,你真正需要“掌握”这个让你觉得直观的概念是Vector方程式的基础知识(都位于Vector原型中),它们如何与每个相互作用(它实际上意味着规范化,或者采取点/标量产品,例如,阅读/与知识渊博的人交谈)以及对碰撞如何作用于物体属性的基本理解(质量,速度等......再次,阅读/与知识渊博的人交谈)

我希望这会有所帮助,祝你好运! -ck

答案 1 :(得分:3)

这是一个非弹性碰撞方程的演示,为您定制:

function BallObject(elasticity) {
  this.v = { x: 1, y: 20 }; // velocity: m/s^2
  this.m = 10; // mass: kg
  this.p = { x: 40, y: 0}; // position
  this.r = 15; // radius of obj
  this.cr = elasticity; // elasticity
}

function draw(obj) {
  ctx.beginPath();
  ctx.arc(obj.p.x, obj.p.y, obj.r, 0, 2 * Math.PI);
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
}

function collide(obj) {
  obj.v.y = (obj.cr * floor.m * -obj.v.y + obj.m * obj.v.y) / (obj.m + floor.m);
}

function update(obj, dt) {

  // over-simplified collision detection
  // only consider the floor for simplicity
  if ((obj.p.y + obj.r) > c.height) { 
     obj.p.y = c.height - obj.r;
     collide(obj);
  }

  obj.v.y += g * dt;
  obj.p.x += obj.v.x * dt * ppm;
  obj.p.y += obj.v.y * dt * ppm;
}

var d = document,
    c = d.createElement('canvas'),
    b = d.createElement('button'),
    els = d.createElement('input'),
    clr = d.createElement('input'),
    clrl = d.createElement('label'),
    ctx = c.getContext('2d'),
    fps = 30, // target frames per second
    ppm = 20, // pixels per meter
    g = 9.8, // m/s^2 - acceleration due to gravity
    objs = [],
    floor = {
      v: { x: 0, y: 0 }, // floor is immobile
      m: 5.9722 * Math.pow(10, 24) // mass of earth (probably could be smaller)
    },
    t = new Date().getTime();

b.innerHTML = 'add ball with elasticity: <span>0.70</span>';
b.onclick = function() { objs.push(new BallObject(els.value / 100)); };

els.type = 'range';
els.min = 0;
els.max = 100;
els.step = 1;
els.value = 70;
els.style.display = 'block';
els.onchange = function() { 
  b.getElementsByTagName('span')[0].innerHTML = (this.value / 100).toFixed(2); 
};

clr.type = 'checkbox';
clr.checked = true;

clrl.appendChild(clr);
clrl.appendChild(d.createTextNode('clear each frame'));

c.style.border = 'solid 1px #3369ff';
c.style.borderRadius = '10px';
c.style.display = 'block';
c.width = 400;
c.height = 400;

ctx.fillStyle = 'rgb(100,200,255)';
ctx.strokeStyle = 'rgb(33,69,233)';

d.body.appendChild(c);
d.body.appendChild(els);
d.body.appendChild(b);
d.body.appendChild(clrl);

setInterval(function() {

  var nt = new Date().getTime(),
      dt = (nt - t) / 1000;

  if (clr.checked) {
    ctx.clearRect(0, 0, c.width, c.height);
  }

  for (var i = 0; i < objs.length; i++) {
    update(objs[i], dt);
    draw(objs[i]);
  }

  t = nt;

}, 1000 / fps);

要亲自动手,请到这里:http://jsbin.com/iwuxol/edit#javascript,live

这利用了这个等式: enter image description here

由于你的“地板”不动,你只需要考虑对球的y速度的影响。请注意,这里有很多快捷方式和疏忽,所以这是一个非常原始的物理引擎,主要是为了说明这一个方程......

希望这有助于确认

答案 2 :(得分:1)

我强烈建议您熟悉center of momentum frame。它使碰撞更多更容易理解。 (如果没有这种理解,你只是在操纵神秘的方程式而且你永远不会知道为什么会出错。)

无论如何,要确定角度,你可以使用影响参数,基本上是“偏离中心”一个球击中另一个球的距离。两个球在相反的方向上(在动量中心框架中)彼此接近,并且它们的中心垂直于那些速度之间的距离是影响参数h。然后偏转角为2 acos(h /(r 1 + r 2 ))。

一旦你完美地运作,你就可以担心非弹性碰撞和恢复系数。