【问题标题】:SFML multiple objects with random values and their collisionsSFML 具有随机值的多个对象及其冲突
【发布时间】:2019-12-11 05:39:54
【问题描述】:

目前我对 SMFL 和 C++ 还很陌生,但在创建非常简单的带球的物理模拟器时遇到了困难。

这是我的 main.cpp:

#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Window/Event.hpp>
#include "ball.hpp"

int main()
{
    /*create window settings*/
    sf::ContextSettings settings;

    /*create window*/
    sf::RenderWindow window;
    window.create(sf::VideoMode(600, 600), "Simple Physics", sf::Style::Default, settings);

    /*create ball(s)*/
    Ball ball;

    /*Main loop*/
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color::Black);

        // call ball.update(); and ball.draw();
        balls.update();
        balls.draw(window);
        window.display();
    }
}

还有ball.hpp:

#include <SFML/Graphics/CircleShape.hpp>

class Ball
{
public:

int minXY = 0;
int maxXY = 600;
int ballRadius = rand() % 50 + 5;        
int random = rand() % maxXY + 1;   //random XY position

    // vector for positions
    //sf::Vector2f pos{random, random};  ->  I Guess this should be included into loop
    sf::Vector2f pos{100, 300};
    // vector for velocity
    sf::Vector2f vel{ 0.1, 0.1 };

    void update()
    {
        // factors influence velocity
       // update position based on velocity
        pos.x += vel.x;
        pos.y += vel.y;

        if (pos.x + ballRadius*2 > maxXY || pos.x < minXY) vel.x = -vel.x; //boundary cond
        if (pos.y + ballRadius*2 > maxXY || pos.y < minXY) vel.y = -vel.y; //boundary cond
    }

    void draw(sf::RenderWindow& window)
    {
        // draw ball to the window using position vector
        sf::CircleShape circle(ballRadius);
        circle.setPosition(pos.x, pos.y);
        circle.setFillColor(sf::Color::White);

        window.draw(circle);
    }
};

现在,我想绘制多个圆形,具有随机大小、速度和颜色。 它们应该在碰撞时反弹,我对此有一些想法,但如果没有多个球就无法真正尝试它们。 我试图用简单的 for 循环来实现它,但它不起作用。 在阅读和观看了许多教程之后,我仍然处于这一点,所以如果有人可以帮助我提供任何工作示例或对我的代码进行一些改进,那就太好了。

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

    我不会给你工作示例,但我认为我可以为你指明正确的方向:

    • 您的 Ball 类需要某种构造函数,并且通过该示例,您可能应该了解更多关于一般类的信息(例如 here)。
    • 然后你应该将你从主循环中生成的球存储在某种container 中。如果您确实知道要生成的球数std::array 应该是您的选择,否则std::vector 是要走的路。
    • 您需要一些函数来检查碰撞,Ball 类的static member 函数应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2017-05-06
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      相关资源
      最近更新 更多