/* * boing.cc * * Created on: Dec 20, 2011 * Author: madura */ #include #include #define LEN 100 using namespace std; struct ball{ int code; float velocity; // S->N positive float position; // measured from south float time; // t=0, start }; typedef list::iterator it_ball; void print(list& balls){ for (it_ball it=balls.begin();it!=balls.end();it++ ) { cout<< it->code<<" pos:"<position<<" velo:"<velocity<< " time:"<time<<"\n"; } } void update_position(ball& b, float time){ b.position += b.velocity*time; b.time += time; if (b.position < 0) b.position = 0; else if (b.position > LEN) b.position = LEN; } float next_collision(ball& a, ball& b) { // Va > Vb && Sb > Sa return (b.position - a.position)/(a.velocity - b.velocity); } void swap(float& a, float& b){ float temp = a; a = b; b = temp; } void update_all_positions(list& balls, float time){ // only for no collisions it_ball it = balls.begin(); while (it!=balls.end()) { update_position(*it,time ); it++; } } void collide(list& balls, float time){ it_ball it = balls.begin(); it = balls.begin(); float collide_in=-1; it_ball collidee; while (it!=--balls.end()) { //it->position += it->velocity*time; it_ball next = it; next++; if ( it->velocity > next->velocity ) { float t = next_collision(*it, *next); if (collide_in>t || collide_in < 0) { collidee = it; collide_in = t; } } it++; } if ( collide_in > 0 ) { if (time > collide_in) { // >= may be? if you take t=collide_in as collided it_ball next=collidee; next++; update_position(*collidee, collide_in); update_position(*next, collide_in); swap(next->velocity,collidee->velocity); collide(balls, time - collide_in); } else { // no collision so update all positions and end update_all_positions(balls, time); } } else {//if ( collide_in < 0 || time <= 0) { // no collision so update all positions and end update_all_positions(balls, time); } } int main(){ list balls; ball a; a.code = 1; a.velocity = 1; a.position = 10; a.time = 0; ball b; b.code = 2; b.velocity =-1; b.position = 95; b.time = 0; balls.push_back(a); balls.push_back(b); print(balls); collide(balls, 60); print(balls); return 0; }