背景与小鸟--FlappyBird游戏开发教程之二

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Good_Developers/article/details/78836797

背景与小鸟–FlappyBird游戏开发教程之二

最终效果:
效果

素材下载:点击下载

EXE效果下载:点击下载

先上代码:

#include <SFML/Graphics.hpp>
#include <windows.h>
#include<iostream>
#include<string>
#include <stdlib.h> 
using namespace std;
double birdX = 50;
double birdY = 100;
#pragma   comment(linker,   "/subsystem:\"windows\"   /entry:\"mainCRTStartup\""   )
int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(288,512), "FlappyBird");

    sf::Texture backgroundtexture;
    if(!backgroundtexture.loadFromFile("assets/background.png"))
    {
    }
    sf::Texture birdtexture;
    if (!birdtexture.loadFromFile("assets/0.png"))
    {
    }

    sf::Sprite backgroundsprite;
    backgroundsprite.setTexture(backgroundtexture);
    sf::Sprite birdsprite;
    birdsprite.setTexture(birdtexture);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        birdsprite.setPosition(sf::Vector2f(birdX, birdY));
        Sleep(20);
        window.clear();
        window.draw(backgroundsprite);
        window.draw(birdsprite);
        window.display();


    }

    return 0;
}

我们来解释一下代码:
先导入了相关头文件;
然后定义了写变量:birdX 和 birdY 就是小鸟的X坐标和Y坐标;

#pragma   comment(linker,   "/subsystem:\"windows\"   /entry:\"mainCRTStartup\""  )

来清除控制台(那个黑框框);

sf::RenderWindow window(sf::VideoMode(宽,长), 题目); 

来创建一个窗口;

    sf::Texture backgroundtexture;
    if(!backgroundtexture.loadFromFile("assets/background.png"))
    {
    }
    sf::Texture birdtexture;
    if (!birdtexture.loadFromFile("assets/0.png"))
    {
    }

以上代码是创建一个材质对象:backgroundtexture
如果backgroundtexture没有加载素材文件,那就加载图片。小鸟的texture代码也一样;

sf::Sprite backgroundsprite;
backgroundsprite.setTexture(backgroundtexture);
sf::Sprite birdsprite;
birdsprite.setTexture(birdtexture);

这些代码的意思是创建SPRITE(精灵)对象,并让它加载材质对象;

while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        Sleep(20);
        window.clear();
        window.draw(backgroundsprite);
        window.draw(birdsprite);
        window.display();


    }

    return 0;
}

这段代码的意思是如果窗口是打开的,就监视事件,如果监视到关闭事件那就关闭窗口。(如果不加,那你的窗口就永远关不掉);
然后延时20毫秒,不然太快,之后让小鸟动时,你啥也看不到;

然后用window.clear();代码清屏;

window.draw(backgroundsprite);
window.draw(birdsprite);

用于代码将两个精灵画到屏幕上

window.display();代码刷新屏幕;

你是不是已经看到在天山飞的小鸟了?赶紧回目录吧!


如果有人评论的话就继续写,没有的话就算了。


展开阅读全文

没有更多推荐了,返回首页