以下是一个简单的C++跑酷游戏代码示例,使用SFML库实现。这个游戏包含一个玩家角色(方块)、障碍物(矩形)和基本的跳跃机制:
#include <SFML/Graphics.hpp>
#include <vector>
#include <cstdlib>
#include <ctime>
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
const float GRAVITY = 0.6f;
const float JUMP_FORCE = -15.0f;
const float OBSTACLE_SPEED = 5.0f;
class Player {
public:
sf::RectangleShape shape;
float velocityY;
Player() {
shape.setSize(sf::Vector2f(50, 50));
shape.setFillColor(sf::Color::Green);
shape.setPosition(100, WINDOW_HEIGHT - 150);
velocityY = 0;
}
void update() {
// 应用重力
velocityY += GRAVITY;
shape.move(0, velocityY);
// 地面碰撞检测
if (shape.getPosition().y > WINDOW_HEIGHT - 150) {
shape.setPosition(100, WINDOW_HEIGHT - 150);
velocityY = 0;
}
}
void jump() {
if (shape.getPosition().y >= WINDOW_HEIGHT - 150) {
velocityY = JUMP_FORCE;
}
}
};
class Obstacle {
public:
sf::RectangleShape shape;
bool passed = false;
Obstacle(float x) {
shape.setSize(sf::Vector2f(30, 80 + rand() % 100));
shape.setFillColor(sf::Color::Red);
shape.setPosition(x, WINDOW_HEIGHT - shape.getSize().y);
}
void update() {
shape.move(-OBSTACLE_SPEED, 0);
}
};
int main() {
srand(time(0));
sf::RenderWindow window(sf::VideoMode

最低0.47元/天 解锁文章
4193

被折叠的 条评论
为什么被折叠?



