【发布时间】:2016-06-24 14:14:28
【问题描述】:
我有一个ball 类型的对象,它是Particle 类的子类。这个类有三个成员position、velocity和acceleration,类型为Vector。
在每一帧上,当调用myball.update 时,它的速度与位置相加,加速度与速度相加。然后球被画在屏幕上。无论如何,对于一些不清楚的动机,无论我给出的速度值是什么,球都不会移动,但如果我给出加速度的值,它会以非加速的匀速运动方式移动。
这是我的类向量:
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 的加速度初始化它,它会移动。
我做错了什么?
【问题讨论】:
-
为什么在位置和速度更新中没有时间分量?
-
你的 Vector 类并不酷。它有 x, y, a, l 作为公共的。此外,参数按值传递给运算符(通常是常量 ref X& operator+=(const X& rhs))。您可以尝试更改操作员签名。你也可以尝试调试你的代码
-
@Unick "也可以尝试调试代码" 对
-
@Unick 我应该将它们设置为私有并实现获取它们的方法吗?不,谢谢。它更慢更冗长(
myvector.getX()而不是myvector.x)。
标签: c++ class inheritance