我得到了一个 ball
类型的对象,它是 Particle
类的子类。该类具有 Vector
类型的三个成员 position
、velocity
和 acceleration
。
在每一帧上,当 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 的加速度初始化它,它就会移动使用加速度作为速度。
我做错了什么?
最佳答案
您在 Particle 构造函数中有错字:
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) {}
关于c++ - 为什么我的球使用加速度作为速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38015545/