1、首先准备游戏需要的背景图片
①跳板图
②人物图
③背景图
2、首先渲染一个400x533的屏幕,然后跳板随机渲染出来。
#include<SFML/Graphics.hpp>
#include<time.h>
using namespace sf;
struct point
{
int x, y;
};
int main()
{
srand(time(0));
RenderWindow app(VideoMode(400, 533), "Doodle Game!");
app.setFramerateLimit(60);
Texture t1, t2, t3;
t1.loadFromFile("./Resources/images/background.png");
t2.loadFromFile("./Resources/images/platform.png");
t3.loadFromFile("./Resources/images/doodle.png");
Sprite sBackground(t1), sPlat(t2), sPers(t3);
point plat[20];
for (int i = 0; i < 10; i++)
{
plat[i].x = rand() % 400;
plat[i].y = rand() % 533;
}
while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
{
app.close();
}
}
app.draw(sBackground);
app.draw(sPers);
for (int i = 0; i < 10; i++)
{
sPlat.setPosition(plat[i].x, plat[i].y);
app.draw(sPlat);
}
app.display();
}
return 0;
}
3、左右移动和自动跳跃
int x = 100;
int y = 100;
int h = 200;
float dx = 0;
float dy = 0;
...
...
if (Keyboard::isKeyPressed(Keyboard::Right))
{
x += 3;
}
if (Keyboard::isKeyPressed(Keyboard::Left))
{
x -= 3;
}
dy += 0.2;
y += dy;
if (y > 500)
{
dy = -10;
}
sPers.setPosition(x, y);
4、模拟实现踏板刚体属性
for (int i = 0; i < 10; i++)
{
if ((x + 50 > plat[i].x) && (x + 20 < plat[i].x + 68) && (y + 70 > plat[i].y) && (y + 70 < plat[i].y + 14) && (dy > 0))
{
dy = -10;
}
}
5、向上自动刷新踏板
#include<SFML/Graphics.hpp>
#include<time.h>
using namespace sf;
struct point
{
int x, y;
};
int main()
{
srand(time(0));
RenderWindow app(VideoMode(400, 533), "Doodle Game!");
app.setFramerateLimit(60);
Texture t1, t2, t3;
t1.loadFromFile("./Resources/images/background.png");
t2.loadFromFile("./Resources/images/platform.png");
t3.loadFromFile("./Resources/images/doodle.png");
Sprite sBackground(t1), sPlat(t2), sPers(t3);
point plat[20];
for (int i = 0; i < 10; i++)
{
plat[i].x = rand() % 400;
plat[i].y = rand() % 533;
}
int x = 100;
int y = 100;
int h = 200;
float dx = 0;
float dy = 0;
while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
{
app.close();
}
}
if (Keyboard::isKeyPressed(Keyboard::Right))
{
x += 3;
}
if (Keyboard::isKeyPressed(Keyboard::Left))
{
x -= 3;
}
dy += 0.2;
y += dy;
if (y > 500)
{
dy = -10;
}
if (y < h)
{
for (size_t i = 0; i < 10; i++)
{
y = h;
plat[i].y = plat[i].y - dy;
if (plat[i].y > 533)
{
plat[i].y = 0;
plat[i].x = rand() % 400;
}
}
}
for (int i = 0; i < 10; i++)
{
if ((x + 50 > plat[i].x) && (x + 20 < plat[i].x + 68) && (y + 70 > plat[i].y) && (y + 70 < plat[i].y + 14) && (dy > 0))
{
dy = -10;
}
}
sPers.setPosition(x, y);
app.draw(sBackground);
app.draw(sPers);
for (int i = 0; i < 10; i++)
{
sPlat.setPosition(plat[i].x, plat[i].y);
app.draw(sPlat);
}
app.display();
}
return 0;
}
结果图:
===============================================================
没有实现暂停,和左右检测功能,以及未能跳到跳板时的触发事件。