1. 程式人生 > 其它 >SDL程式設計入門(31)滾動背景

SDL程式設計入門(31)滾動背景

技術標籤:SDL2 教程中心SDL滾動遊戲開發

滾動背景

通常在遊戲中,你可能想要一個無限或迴圈的背景。使用滾動背景,你可以迴圈一個永遠持續下去的背景。

比如說,如果我們想在一個無限的背景上圍繞一個點移動:

我們要做的就是將背景的兩次迭代彼此相鄰渲染,並將它們每幀移動一點。 當背景完全移開時,你可以重新設定運動:

//The dot that will move around on the screen
class Dot
{
    public:
        //The dimensions of the dot
        static const int DOT_WIDTH =
20; static const int DOT_HEIGHT = 20; //Maximum axis velocity of the dot static const int DOT_VEL = 10; //Initializes the variables Dot(); //Takes key presses and adjusts the dot's velocity void handleEvent( SDL_Event& e ); //Moves the dot
void move(); //Shows the dot on the screen void render(); private: //The X and Y offsets of the dot int mPosX, mPosY; //The velocity of the dot int mVelX, mVelY; };

在本教程中,我們將使用僅保留在螢幕上的純色圓點。

            //螢幕上將要移動的點
            Dot dot;

            //背景滾動偏移
int scrollingOffset = 0;

在進入主迴圈之前,我們宣告一個Dot物件和滾動偏移。

                //Move the dot
                dot.move();

                //滾動背景
                --scrollingOffset;
                if( scrollingOffset < -gBGTexture.getWidth() )
                {
                    scrollingOffset = 0;
                }

在這裡,我們要更新點並更新滾動背景。

更新滾動背景的位置只是遞減x的位置,如果x的位置小於背景的寬度,說明背景已經完全離屏,需要重新設定位置。

                //Clear screen
                SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
                SDL_RenderClear( gRenderer );

                //Render background
                gBGTexture.render( scrollingOffset, 0 );
                gBGTexture.render( scrollingOffset + gBGTexture.getWidth(), 0 );

                //Render objects
                dot.render();

                //Update screen
                SDL_RenderPresent( gRenderer );

在這裡,我們渲染背景和點。 首先,我們通過渲染紋理的兩次迭代來渲染滾動背景,然後在其上渲染點。 這樣我們就可以得到一個平滑滾動的無限背景的效果。

這裡下載本教程的媒體和原始碼。

原文連結

關注我的公眾號:程式設計之路從0到1
程式設計之路從0到1