【发布时间】: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 循环来实现它,但它不起作用。 在阅读和观看了许多教程之后,我仍然处于这一点,所以如果有人可以帮助我提供任何工作示例或对我的代码进行一些改进,那就太好了。
【问题讨论】: