我有一个ball
类型的对象,它是类Particle
的子类。此类有三个position
,velocity
和acceleration
Vector
类型的成员。
在每个帧上,当调用myball.update
时,其速度与该位置相加,并且加速度与速度相加。然后球在屏幕上绘制。无论如何,对于一些不明确的动机,无论我给出的任何值作为速度,球都不会移动,但是如果我给出加速度的值,它会以非加速的均匀运动移动。
这是我的课程Vector:
class Vector {
private:
void updateC() {
x = cos(a) * l;
y = sin(a) * l;
}
void updateT() {
a = atan2(y, x);
l = sqrt(x * x + y * y);
}
public:
float x = 0, y = 0;
float a = 0, l = 0;
Vector() {
}
Vector(float nx, float ny): x(nx), y(ny) {
updateT();
}
void X(float nx) {
x = nx;
updateT();
}
void Y(float ny) {
y = ny;
updateT();
}
void A(float na) {
a = na;
updateC();
}
void L(float nl) {
l = nl;
updateC();
}
Vector operator +(Vector other) {
return Vector(x + other.x, y + other.y);
}
Vector operator -(Vector other) {
return Vector(x - other.x, y - other.y);
}
Vector operator *(float m) {
Vector result(x, y);
result.L(l * m);
return result;
}
void operator +=(Vector other) {
x += other.x;
y += other.y;
updateT();
}
void operator -=(Vector other) {
x -= other.x;
y -= other.y;
updateT();
}
void operator *=(float m) {
l *= m;
updateC();
}
};
粒子:
class Particle {
public:
Vector position;
Vector velocity;
Vector gravity;
Particle() {}
Particle(Vector np, Vector nv = Vector(0, 0), Vector na = Vector(0, 0)): position(np), velocity(na), gravity(na) {}
void accelerate(Vector a) {
velocity += a;
}
void update() {
position += velocity;
velocity += gravity;
}
};
和球:
class ball: public Particle {
public:
ball(Vector p, Vector v, Vector a): Particle(p, v, a) {}
void update() {
Particle::update();
graphics.circle("fill", position.x, position.y, 10);
}
};
所以,正如我之前所说,如果我以不同于0的速度初始化myball
,球仍然不会移动,但如果我使用不同于0的加速度初始化它,它将会移动以速度加速。
我做错了什么?
答案 0 :(得分:3)
您在粒子构造函数中输入错误:
Particle(Vector np, Vector nv = Vector(0, 0), Vector na = Vector(0, 0)): position(np), velocity(na), gravity(na) {}
必须是:
Particle(Vector np, Vector nv = Vector(0, 0), Vector na = Vector(0, 0)): position(np), velocity(nv), gravity(na) {}