So I'm making a 2D vector class for a class where I create collisions between circular objects with mass and radius on a x-y plane. So everytime a collision happens, I need to update the velocity of the two circles that collided and this relies upon scalar numbers like mass and radius as well as the kinetic energy (scalar) and the momentum (2d vector) of the stones (since momentum and energy conserved , you can solve the momentum and energy of either). All the methods work except for the scalar multiplication. I will only display that method below unless you guys specifically request for me to show the others
Here's my 2d vector class
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 };
}
Here's the method in the other class that does the updates the velocity after collision
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;
}
Here's the methods that calculate energy and momentum
double energy() const {
return 0.5 * (mass * velocity * velocity) ;
}
// Calculates the momentum of the balls
vec2d momentum() const {
return mass * velocity;
}
Here are the errors that are produced:
error: no match for 'operator*' (operand types are 'double' and 'vector2d')
error: no match for 'operator*' (operand types are 'const double' and 'vector2d')
Let me know if I should put more information
Your code multiples a double
to a vector2d
. That won't activate the operator, because the operator will expect a vector2d
first. You should have either
vec2d v1 = this->velocity - (diff_pos_s1 * (mass_ratio_s1 * (num_s1 / denom_s1)));
or write an vector2d operator*(double, vector2d)
, for instance
vector2d operator *(const double & scalar, const vector2d & other) {
return { other.x * scalar, other.y*scalar };
}
As an aside, it seems a waste of time to me to use a reference on a const double
.