/* In this example we look at basic forces acting on a single object. We'll use gravity, wind and drag to move our object about the screen. */ SimObject so; boolean showVectors = true; PFont labelFont; void setup() { // setup the processing environment size(300, 400); background(10); colorMode(RGB, 255, 255, 255, 255); framerate(20); // load our font labelFont = loadFont("LucidaGrande-32.vlw"); textFont(labelFont, 14); // create our SimObject Vector2D a = new Vector2D(0.0,0.0); Vector2D v = new Vector2D(0.0,0.0); Vector2D l = new Vector2D(150,10); so = new SimObject(a, v, l, 1.5); } void draw() { // reset our background background(10); // add gravity to our object /* Note that these are made up values for gravity, for the sake of giving our simulation a "feeling" of reality. */ Vector2D gravity = new Vector2D(0, 0.2); so.addForce(gravity); drawOverlay(gravity, so.getLocation(), 200, "Gravity"); // add "wind" to the object /* Again, we're making up values for this. */ Vector2D wind = new Vector2D(0.0, -0.01); so.addForce(wind); drawOverlay(wind, so.getLocation(), 200, "Wind"); // add friction (drag) to our object /* We'll define an area of the screen that has "friction" that slows down our object as it moves through. Drag is calculated as being an opposing force to the velocity of the object, so we'll use the value of our object's velocity to calculate the drag force. */ float drag_start = 200.0; float drag_height = 100.0; // determine if we're inside of the drag area if ( (so.getLocation().getY() > drag_start) && (so.getLocation().getY() < drag_start + drag_height) ) { // set our coefficient of friction float c = -0.03f; // get our current velocity Vector2D objectVelocity = so.getVelocity(); // determine the drag force Vector2D drag = objectVelocity.multiply(c); // add the drag force so.addForce(drag); drawOverlay(drag, so.getLocation(), 200, "Friction"); } // set our simulation in motion so.simulate(); // draw the drag area noStroke(); fill(128, 16, 16, 225); rectMode(CORNER); rect(0, drag_start, width, drag_height); } /* This is our utility function for drawing overlays describing the force vectors acting on our object. */ void drawOverlay(Vector2D v, Vector2D location, float scale, String name) { if (showVectors == true) { // save our drawing environment pushMatrix(); // move to our position to draw our force vector translate(location.getX(), location.getY()); // drawing settings stroke(255); float arrowSize = 10; float arrowLength = v.magnitude() * scale; // rotate so that the direction of our drawing is the heading // of our vector rotate(v.heading()); // draw the arrow line(0, 0, arrowLength, 0); line(arrowLength, 0, arrowLength - arrowSize, arrowSize / 2); line(arrowLength, 0, arrowLength - arrowSize, arrowSize / 2 * -1); // label our arrow fill(255, 255, 255, 255); text(name, arrowLength, 0); // reset our drawing environment popMatrix(); } } void mousePressed() { showVectors = !showVectors; }