Lalo_Salamanka 2023-01-19 20:33 采纳率: 33.3%
浏览 58
已结题

c++弹跳小球添加颜色

希望给小球和背景加上颜色
(凑字数ing)(czsawdawda)
给小球加上颜色
  • 写回答

2条回答 默认 最新

  • Rednblack· 2023-01-28 19:22
    关注
    #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;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月19日
  • 已采纳回答 6月11日
  • 创建了问题 1月19日