I need to optimize to the maximum the algorithm that makes the collision between the particles, is there anything that can be done for this? And I also want to add a background image, is it possible?
Follow the code canvas.cpp:
canvas::canvas(QWidget *parent) :
QWidget(parent)
{
m_particulas.resize(20);
int n = m_particulas.size();
for(int i = 0 ; i<n ; ++i)
{
m_particulas[i].init();
}
startTimer(10);
}
void canvas::paintEvent(QPaintEvent * event)
{
(void) event;
QPainter painter(this);
painter.setWindow(0,0,1000,1000);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, 5, Qt::SolidLine, Qt::RoundCap));
painter.setBrush(QBrush(Qt::darkCyan, Qt::SolidPattern));
int n = m_particulas.size();
for(int i = 0 ; i<n ; ++i)
{
double x = m_particulas[i].x();
double y = m_particulas[i].y();
double L = m_particulas[i].r();
painter.drawEllipse(QPointF(x, y), L, L);
}
}
void canvas::timerEvent(QTimerEvent *event)
{
(void) event;
int n = m_particulas.size();
for(int i = 0 ; i<n ; ++i)
{
m_particulas[i].andar();
Particula &pi = m_particulas[i];
for(int j = 0 ; j < n ; ++j)
{
if (i == j) continue;
Particula &pj = m_particulas[j];
if (pi.testa_colisao(pj))
{
pi.calcula_colisao(pj);
}
}
pi.andar();
}
update();
}
particulas.cpp:
Particula::Particula()
{
}
void Particula::init()
{
m_r = 20;
m_x = 900.0*rand()/RAND_MAX + 50;
m_y = 900.0*rand()/RAND_MAX + 50;
m_vx = 2.0 * rand()/RAND_MAX - 1;
m_vy = 2.0 * rand()/RAND_MAX - 1;
double norma = sqrt(m_vx*m_vx + m_vy*m_vy);
m_vx /= norma;
m_vy /= norma;
}
void Particula::normaliza(double &vx, double &vy)
{
double norma = sqrt(vx*vx + vy*vy);
if (norma > 0)
{
vx /= norma;
vy /= norma;
}
}
bool Particula::testa_colisao (Particula &p)
{
double dx = x() - p.x();
double dy = y() - p.y();
double dist = sqrt(dx*dx + dy*dy);
return dist <= r() + p.r();
}
void Particula::calcula_colisao(Particula &p)
{
double vx = p.x() - x();
double vy = p.y() - y();
normaliza(vx,vy);
p.m_vx += vx;
p.m_vy += vy;
normaliza(p.m_vx,p.m_vy);
m_vx -= vx;
m_vy -= vy;
normaliza(m_vx, m_vy);
while (testa_colisao(p))
{
andar();
p.andar();
}
}
double Particula::x() const
{
return m_x;
}
double Particula::y() const
{
return m_y;
}
double Particula::r() const
{
return m_r;
}
void Particula::andar()
{
m_x += m_vx;
m_y += m_vy;
if(m_x > 1000-m_r) m_vx *= -1; //inferior - multiplicado por -1 para inverter a direção...
if(m_y > 1000-m_r) m_vy *= -1; //direita
if(m_x < 0+m_r) m_vx *= -1; //esquerda
if(m_y < 0+m_r) m_vy *= -1; //superior
}