两个对象之间的碰撞响应

时间:2016-04-08 05:38:16

标签: javascript html5 canvas collision-detection

我正在开发physics engine for my Canvas library,专门处理碰撞响应。目前使用我发现的片段的修改版本,但计算结果为零速度。

Example fiddle.

Art.prototype.modules.physics.response = function(a, b) {

  var rotate = function(x, y, sin, cos, reverse) {

    return {
      x: (reverse) ? (x * cos + y * sin) : (x * cos - y * sin),
      y: (reverse) ? (y * cos - x * sin) : (y * cos + x * sin)
    };

  }

  var dx = b.x - a.x,
    dy = b.y - a.y,
    angle = Math.atan2(dy, dx),
    sin = Math.sin(angle),
    cos = Math.cos(angle),
    position = {
      x: 0,
      y: 0
    },
    _position = rotate(dx, dy, sin, cos, true),
    velocity = rotate(a.velocity.x, a.velocity.y, sin, cos, true),
    _velocity = rotate(b.velocity.x, b.velocity.y, sin, cos, true),
    total = velocity.x - _velocity.x,
    offset = a.boundaries().width,
    _offset = b.boundaries().width;

  velocity.x = ((a.mass - b.mass) * velocity.x + 2 * b.mass * _velocity.x) / (a.mass + b.mass);

  _velocity.x = total + velocity.x;

  var abs = Math.abs(velocity.x) + Math.abs(_velocity.x),
    overlap = (offset + _offset) - Math.abs(position.x - _position.x);

  position.x += velocity.x / abs * overlap;

  _position.x += _velocity.x / abs * overlap;

  var positionF = rotate(position.x, position.y, sin, cos, false),
      _positionF = rotate(_position.x, _position.y, sin, cos, false);

  b.x = a.x + _positionF.x;
  b.y = a.y + _positionF.y;
  a.x = a.x + positionF.x;
  a.y = a.y + positionF.y;

  var velocityF = rotate(velocity.x, velocity.y, sin, cos, false),
    _velocityF = rotate(_velocity.x, _velocity.y, sin, cos, false);

  a.velocity.x = velocityF.x;
  a.velocity.y = velocityF.y;
  b.velocity.x = _velocityF.x;
  b.velocity.y = _velocityF.y;

  return this.response.core;

};

控制台显示没有错误,但多边形立即失去其位置和速度(因为值为NaN而恢复为0)。我在这里做错了什么?

0 个答案:

没有答案