// Bryan Blackford - bblackfo@ucsc.edu // individual car of train class Traincar { float xpos,ypos; //position(top left) float rot; //wheel rotation (radians) int wheelradius; //wheel size int carlength; // hitch to hitch length int carheight; // height of car, not including wheels int wheelspace; //space from ends of car to center of wheels boolean alive; // draw car? int moveSpeed; Traincar(float x, float y, int Carlength) //constructor { // init vars xpos=x; ypos=y; carlength=Carlength; carheight=15; rot=0; wheelradius=3; wheelspace =6; moveSpeed = 1; alive = true; } void update() { xpos -= moveSpeed; // move train if (alive) { // spin wheel rot -= .1; // radians // keep rotation in [0-360) while (rot >= 360) rot -= 360; while (rot < 0) rot += 360; draw(); } } void draw() // draw car { pushMatrix(); // push matrix on transform stack translate(xpos,ypos); // transform:shift to car pos // draw box of car stroke(255); noFill(); // hollow rect(1,0,carlength-2,CarBottom()); //box of car point(0,CarBottom()); // front hitch point(carlength,CarBottom()); // rear hitch // draw wheels ellipse( wheelspace,CarBottom()+wheelradius,wheelradius*2,wheelradius*2); // front wheel ellipse(carlength-wheelspace,CarBottom()+wheelradius,wheelradius*2,wheelradius*2); // rear wheel // front spokes pushMatrix(); // push another matrix on stack for front spokes translate(wheelspace,CarBottom()+wheelradius); // xform: center of wheel rotate(rot); // rotate about axle line(-wheelradius,0,wheelradius,0); //horizontal line line(0,-wheelradius,0,wheelradius); //vertical line popMatrix(); // pop front spoke transform // rear spokes pushMatrix(); // shift and rotate translate(carlength-wheelspace,CarBottom()+wheelradius); rotate(rot); line(-wheelradius,0,wheelradius,0); //hline line(0,-wheelradius,0,wheelradius); //vline popMatrix(); // pop rear spoke /* these spokes work fine, but rotate() above is better float cr = cos(rot); float cr2 = cos(rot+(PI/2)); float sr = sin(rot); float sr2 = sin(rot+(PI/2)); line(4 +(cr*3),12+(sr*3),4 -(cr*3),12-(sr*3)); line(4 +(cr2*3),12+(sr2*3),4 -(cr2*3),12-(sr2*3)); line(16+(cr*3),12+(sr*3),16-(cr*3),12-(sr*3)); line(16+(cr2*3),12+(sr2*3),16-(cr2*3),12-(sr2*3)); */ popMatrix(); // pop translation matrix } // coordinate of bottom of car wheels int CarBottom() { return carheight-(wheelradius*2); } }