为2d向量类

时间:2018-05-05 18:43:00

标签: c++ class game-physics

所以我正在为一个类创建一个2D矢量类,我在x-y平面上创建质量和半径的圆形对象之间的碰撞。因此,每次发生碰撞时,我都需要更新碰撞的两个圆的速度,这依赖于质量和半径等标量数以及石头的动能(标量)和动量(2d矢量)(因为动量)和能量守恒,你可以解决其中的动量和能量)。除了标量乘法之外,所有方法都有效。我只会在下面显示这种方法,除非你们特别要求我展示其他人

这是我的2d矢量类

class vector2d {
  public:
     double x;
     double y;
     // Constructor
     vector2d() { x=0; y=0; }
     vector2d(double_x, double_y) { x=_x; y=_y;}
     .
     .
     .
     vector2d operator*(const double& scalar) const {
     return {x * scalar, y * scalar };
     }

这是另一个类中用于更新碰撞后速度的方法

void collide(Ball *s) {
  // Make sure move is called before this to update the position vector'
  vec2d diff_pos_s1 = this->init_pos - s->init_pos;
  vec2d diff_vel_s1 = this->velocity - s->velocity;
  double mass_ratio_s1 = (2 * s->mass) / (this->mass + s->mass);
  double num_s1 = diff_pos_s1.dot_product(diff_vel_s1);
  double denom_s1 = diff_pos_s1.dot_product(diff_pos_s1);
  vec2d v1 = this->velocity - (mass_ratio_s1 * (num_s1 / denom_s1) * diff_pos_s1);

  vec2d diff_pos_s2 = s->init_pos - this->init_pos;
  vec2d diff_vel_s2 = s->velocity - this->velocity;
  double mass_ratio_s2 = (2 * this->mass) / (this->mass + s->mass);
  double num_s2 = diff_vel_s2.dot_product(diff_pos_s2);
  double denom_s2 = diff_pos_s2.dot_product(diff_pos_s2);
  vec2d v2 = s->velocity - (mass_ratio_s2 * (num_s2 / denom_s2) * diff_pos_s2);

  this->velocity = v1;
  s->velocity = v2;
}

这是计算能量和动量的方法

double energy() const {
  return 0.5 * (mass * velocity * velocity) ;
}
// Calculates the momentum of the balls
vec2d momentum() const {
  return mass * velocity;
}

以下是产生的错误:

error: no match for 'operator*' (operand types are 'double' and 'vector2d')
error: no match for 'operator*' (operand types are 'const double' and 'vector2d')

让我知道是否应该提供更多信息

1 个答案:

答案 0 :(得分:1)

您的代码将vector2d乘以vector2d。这不会激活运营商,因为运营商首先会期望vec2d v1 = this->velocity - (diff_pos_s1 * (mass_ratio_s1 * (num_s1 / denom_s1))); 。你应该有

vector2d operator*(double, vector2d)

或写一个vector2d operator *(const double & scalar, const vector2d & other) { return { other.x * scalar, other.y*scalar }; } ,例如

const double

顺便说一句,在# A tibble: 7 x 7 Household_size q_1 q_2 q_3 q_4 q_5 q_6 <int> <int> <int> <int> <int> <int> <int> 1 3 1 2 1 NA NA NA 2 2 2 1 NA NA NA NA 3 5 1 2 1 1 2 NA 4 3 2 2 1 NA NA NA 5 6 2 1 1 1 1 1 6 5 1 2 1 2 2 NA 7 3 1 2 2 NA NA NA 上使用引用似乎是浪费时间。