namespace pars { const float Dt=0.1; // l'intervallo di tempo } class vett { public: vett(float x=0., float y=0.) : theX(x), theY(y) {} float x() const { return theX; } float y() const { return theY; } vett operator-() const { return vett(-x(), -y()); } // inverso private: float theX, theY; }; vett operator*(const float& s, const vett& v) { // s*v (prodotto per scalare) return vett(s*v.x(), s*v.y()) ; } vett operator*(const vett& v ,const float& s ) { // v*s (prodotto per scalare e' commutativo) return s*v; } vett operator+(const vett& a, const vett& b) { // a+b return vett(a.x()+b.x(), a.y()+b.y()); } vett operator-(const vett& a, const vett& b) { // a-b return a+(-b); } ostream& operator<<(ostream& out, const vett& v) { // cout << v out << "("<< v.x() << "," << v.y() << ")" ; return out; } class palla { public: palla(float m, vett pos = vett(), vett vel = vett()) : theM(m), thePos(pos), theVel(vel) {} float m() const {return theM;} vett pos() const { return thePos; } vett vel() const { return theVel; } void evolvi(const vett& Forza) { // qui devo mettere le eq del moto cinematiche: mi serve ( pars::Dt ) vett a=Forza*(1./m()); theVel=theVel+a*pars::Dt; thePos=thePos+vel()*pars::Dt; } void controllaBordi(float minx, float maxx, float miny, float maxy) { if (pos().x()<=minx || pos().x() >=maxx) theVel=vett(-vel().x(), vel().y()); if (pos().y()<=miny || pos().y() >=mayy) theVel=vett(vel().x(), -vel().y()); } private: const float theM ; // the mass vett thePos, theVel; }; class scatola { public: scatola(float minx=0., float maxx=100., float miny=0., float maxy=100.) : theMinX(minx), theMaxX(maxx), theMinY(miny), theMaxY(maxy) { theP1=palla(1., vett(10,10)); // inizialmente ferma theP2=palla(10., vett(20,20)); // inizialmente ferma } void evolvi() { // calcolo la forza risultante su P1 e P2 vett F1; // gravita' // F1=F1+gravita; F1 = F1 + theP1.m()*vett(0.,pars::g); // forza elastica // F1=F1+Fel; // distanza tra le due palle vett dist=theP1.pos()-theP2.pos(); // Fel=-k*dist F1 = F1 + -(pars::k)*dist; // idem per P2 vett F2 = theP2.m()*vett(0.,pars::g); F2 = F2 + (pars::k)*dist; // 3o principio dimanica // faccio evolvere P1 e P2 theP1.evolvi(F1); theP2.evolvi(F2); // controllo se P1 e P2 hanno raggiunto i bordi theP1.controllaBordi(theMinX, theMaxX, theMinY, theMaxY); theP2.controllaBordi(theMinX, theMaxX, theMinY, theMaxY); } void display() { cout << "P1: " << theP1 << " | P2 = " << theP2 << endl; } private: palla theP1, theP2; float theMinX, theMaxX, theMinY, theMaxY; }; int main(int maxIter = 100) { scatola s; for (int i=0; i< maxIter; ++i ) { s.evolvi(); s.display(); } return 0; }