Next, what we really want is for our invaders to start off the right edge of the screen and move towards the left. You may have noticed that when I drew the invaders, they are spaced 70 pixels apart and they all have an offset in the x direction of 0.
If we change this 0 to something else - a variable that controls how far along they are, they will all move together, but kill 70 pixels spacing. Actually, since we are drawing multiple things at this position, it makes a lot more sense to use translate(), like so:
int[] invaders;
float offset;
void setup() {
size(800, 300);
invaders = new int[800/35];
for ( int i = 0; i < invaders.length; i++) {
invaders[i] = 6;
}
}
void draw() {
background(0);
offset = mouseX;
// Draw all invaders.
for ( int i = 0; i < invaders.length; i++) {
if ( invaders[i] != -1 ) {
rectMode(CENTER);
pushMatrix();
translate(width - offset + i * 70, height/2);
fill(255);
rect(0, 0, 40, 40);
fill(0);
text(invaders[i], 0, 0);
popMatrix();
}
}
}
Run this and verify for yourself that changing the mouseX amount changes the offset variable which controls where the invaders are drawn. Now we change the offset variable a bit, and it looks like our invaders are moving in from the right:
int[] invaders;
float offset;
void setup() {
size(800, 300);
invaders = new int[800/35];
for ( int i = 0; i < invaders.length; i++) {
invaders[i] = 6;
}
offset = -70;
}
void draw() {
background(0);
offset++;
// Draw all invaders.
for ( int i = 0; i < invaders.length; i++) {
if ( invaders[i] != -1 ) {
rectMode(CENTER);
pushMatrix();
translate(width - offset + i * 70, height/2);
fill(255);
rect(0, 0, 40, 40);
fill(0);
text(invaders[i], 0, 0);
popMatrix();
}
}
}