首先,你需要在C + +代码中添加一个变量来存储颜色值。然后,在“void draw()”函数中,使用“glColor3f(R,G,B)”函数将该颜色值传递给OpenGL。在这里,R,G和B表示红色,绿色和蓝色分量。最后,在渲染循环中使用“glClearColor(R,G,B,A)”函数设置背景颜色。它的参数与前面的相同,但是它的A参数表示alpha值,可以用来控制背景颜色的不透明度。
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include <ctime>
int main()
{
// 创建游戏窗口
sf::RenderWindow window(sf::VideoMode(800, 600), "Bouncing Ball");
// 创建小球
sf::CircleShape ball(25.0f);
ball.setFillColor(sf::Color::Red);
ball.setPosition(400.0f, 300.0f);
// 设置小球的速度
sf::Vector2f velocity(5.0f, 5.0f);
// 初始化随机数生成器
std::srand(std::time(NULL));
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
// 更新小球位置
ball.move(velocity);
// 检查小球是否碰到边界
if ((ball.getPosition().x + ball.getRadius() > window.getSize().x && velocity.x > 0) ||
(ball.getPosition().x - ball.getRadius() < 0 && velocity.x < 0))
{
velocity.x = -velocity.x;
//随机改变颜色
ball.setFillColor(sf::Color(rand() % 255,rand() % 255,rand() % 255));
}
if ((ball.getPosition().y + ball.getRadius() > window.getSize().y && velocity.y > 0) ||
(ball.getPosition().y - ball.getRadius() < 0 && velocity.y < 0))
{
velocity.y = -velocity.y;
//随机改变颜色
ball.setFillColor(sf::Color(rand() % 255,rand() % 255,rand() % 255));
}
window.clear();
window.draw(ball);
window.display();
}
return 0;
}