The picture on the right shows the two possible displays from the sketch code below. Clicking the mouse button flips between them.
In the left picture no translation has been applied and the green box is not visible because its coordinates are offscreen.
In the right picture the only difference is that the matrix has been translated by [120,150] before drawing. The green box is now visible.
It is often the case that some graphical elements (e.g. 2D controls such as a check box) should
always appear in the same place. In this sketch this is simulated with the blue circle.
To get this effect I have used the pushMatrix function tol save the matrix before translation and the popMatrix which restores the last saved matrix. BTW it is important that there is a popMatrix for every pushMatrix and vica-versa.
- int tx, ty;
- void setup() {
- size(300, 300);
- tx = 0;
- ty = 0;
- }
- void draw() {
- background(0);
- pushMatrix(); // Save the matrix
- translate(tx, ty);
- // Two yellow shapes
- fill(255, 255, 0);
- ellipse(100, 140, 30, 40);
- rect(30, 10, 100, 30);
- // Green shape
- fill(0, 255, 0);
- rect (-40, - 80, 30, 70);
- popMatrix(); // Restore the matrix
- // Everything drawn after this will not move
- fill(0, 0, 255);
- ellipse(150, 150, 20, 20);
- }
- void mouseClicked() {
- if (tx == 0) {
- tx = 120;
- ty = 150;
- }
- else {
- tx = 0;
- ty = 0;
- }
- }
HTH