【发布时间】:2018-10-16 00:02:06
【问题描述】:
所以我正在为一个类创建一个 2D 矢量类,在该类中,我在 x-y 平面上创建具有质量和半径的圆形对象之间的碰撞。所以每次发生碰撞时,我都需要更新碰撞的两个圆的速度,这取决于像质量和半径这样的标量数字以及石头的动能(标量)和动量(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')
如果我应该提供更多信息,请告诉我
【问题讨论】:
-
你能提供一个minimal reproducible example吗?您只需要提供足够的代码来说明您的重载运算符。
collide()函数比说明这一点所需的复杂得多。我建议使用您的vector2d类创建一个文件,并且只创建您的问题所需的成员。还包括一个main()函数来说明你想要做什么。当您在此处发布代码时,任何人都应该能够复制和粘贴它并得到与您所询问的完全相同的编译器错误。
标签: c++ class game-physics