奇怪的行为发现了 c++ sdl2

Strange behavior spotted c++ sdl2

本文关键字:c++ sdl2 发现      更新时间:2023-10-16

使用 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 变量执行任何操作。

知道为什么它不递增吗?

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