首页 文章

为什么我的球使用加速度作为速度?

提问于
浏览
0

我有一个 ball 类型的对象,它是类 Particle 的子类 . 该类有三个成员 positionvelocityacceleration ,类型为 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的加速度初始化它,它将移动 .

我做错了什么?

1 回答

  • 3

    你在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) {}
    

相关问题