【问题标题】:Strange behavior spotted c++ sdl2发现奇怪的行为 c++ sdl2
【发布时间】:2019-06-07 21:09:33
【问题描述】:

使用 sdl2,我设法为游戏构建了“即将成为意大利面”的类。然而,当涉及到使用类的函数时,我偶然发现了这种奇怪之处。


class Player{
    public:
        Player();
        const SDL_Rect *getPositionPtr() const { return &position; }
        const SDL_Rect * getClip(){ return &clip; }
        void eventHandle(SDL_Event & e);
        void move();

    private:
        SDL_Rect position;
        SDL_Rect clip;


        float velocity;
        bool leftkeydown;
        bool rightkeydown;
};

Player::Player(){
    position = {100, 300, 64, 64};
    clip = {0, 0, 64, 64};

    velocity = 0.3;
    leftkeydown = false;
    rightkeydown = false;
}

void Player::eventHandle(SDL_Event & e){
    if( e.type == SDL_KEYDOWN && e.key.repeat == 0 ){
        switch( e.key.keysym.sym ){
            case SDLK_a:
                leftkeydown = true;
                break;

            case SDLK_d:
                rightkeydown = true;
                break;
        }
    }
    else if( e.type == SDL_KEYUP && e.key.repeat == 0 ){
        //Adjust the velocity
        switch( e.key.keysym.sym ){
            case SDLK_a:
                leftkeydown = false;
                break;

            case SDLK_d:
                rightkeydown = false;
                break;
        }
    }
}

void Player::move(){
    if(leftkeydown) position.x -= velocity;
    if(rightkeydown) position.x += velocity; // <----- problem here
}

leftkeydown 似乎按预期工作,但 rightkeydown 对 position.x 变量没有任何作用。

任何想法为什么它不增加?

【问题讨论】:

  • 你是如何测试这个的?您是否确保至多leftkeydownrightkeydown 之一在任何给定点为真?
  • 你的速度是 0.3,positionSDL_Rect,由四个整数组成。 100 - 0.3 是 99,但 100 + 0.3 仍然是 100。

标签: c++ sdl-2


【解决方案1】:

正如 @keltar 所称赞的那样,因为在 int + (float 处,int 保持不变,因为它转换了结果(100.3) 从 floatint (100) (这是因为其中一个值是 int)所以位置 x 将保持不变,除非您将速度设为 int 或更大大于 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    相关资源
    最近更新 更多