Я программирую на c++ и использую графическую библиотеку SFML.
#include <SFML/Graphics.hpp>
using namespace sf;
using namespace std;
class Ball //Класс шара
{
public:
Ball(double radius, Color color, double x, double y, double dx, double dy) //dy и dx - направления шара
{
this->radius = radius;
this->color = color;
this->x = x;
this->y = y;
this->dx = dx;
this->dy = dy;
}
void draw(RenderWindow& window, CircleShape& shape) //Рисуем шар
{
shape.setFillColor(this->color);
shape.setRadius(this->radius);
shape.setOrigin(this->radius, this->radius);
shape.setPosition(this->x, this->y);
window.draw(shape);
}
void move(int winSize) //Двигаем шар
{
this->x += this->dx;
this->y += this->dy;
if (this->y < this->radius)
{
this->dy = -this->dy;
this->y = this->radius;
}
else if (this->y > winSize - this->radius)
{
this->dy = -this->dy;
this->y = winSize - this->radius;
}
if (this->x < this->radius)
{
this->dx = -this->dx;
this->x = this->radius;
}
else if (this->x > winSize - this->radius)
{
this->dx = -this->dx;
this->x = winSize - this->radius;
}
}
void update(RenderWindow& window, CircleShape& shape, int winSize) //Сначала двигаем шар, а потом рисуем
{
this->move(winSize);
this->draw(window, shape);
}
private:
double radius;
Color color;
double y;
double x;
double dy;
double dx;
};
int main()
{
const int winSize = 900;
RenderWindow window(VideoMode(winSize, winSize), "Ball"); //Окно
CircleShape shape(0);
Ball ball(30, Color(255, 255, 0), 300, 450, 3, 2); //Шар
while (window.isOpen())
{
Event event;
while (window.pollEvent(event)) //Проверка событий
{
switch (event.type)
{
case Event::Closed:
window.close();
break;
default:
break;
}
}
window.clear();
ball.update(window, shape, winSize); //Двигаем и рисуем шар
window.display();
}
}
В Ball ball(30, Color(255, 255, 0), 300, 450, 3, 2);
создаётся шар и с помощью ball.update(window, shape, winSize);
двигается и выводится на экран. Но что делать, если я хочу создать больше шаров, например 100? Можно создать массив balls
, указать его размер в const int numberOfBalls
и заполнить его шарами, а потом ball.update(window, shape, winSize);
заменить на
for (int i = 0; i < numberOfBalls; i++)
{
balls[i].update(window, shape, winSize);
}
вызывая у каждого шара функцию update()
. Но у меня не получается заполнить массив шарами. Я попробовал создать и заполнить массив шарами так
const int numberOfBalls = 100;
Ball balls[numberOfBalls];
for (int i = 0; i < numberOfBalls; i++)
{
balls[i] = ball(30, Color(255, 255, 0), 300, 450, 3, 2);
}
Но visual studio говорит, что есть 2 ошибки. Первая в Ball balls[numberOfBalls];
, что нету конструктора по умолчанию, а вторая в balls[i] = ball(30, Color(255, 255, 0), 300, 450, 3, 2);
, что идентификатор ball
не определён.