The second program is an attempt to create a Star Wars type lightspeed effect whilst using the program from the chunk. The end result looks like this:

// the number of stars
int numberOfStars;
// coordinates of the vertices
float[][] vertexCoords;
// speed (number of pixels) that the vertices move in the x direction
int xSpeed;
// speed (number of pixels) that the vertices move in the x direction
int ySpeed;
void setup() {
// setup display variables
size(600, 400);
background(0);
smooth();
strokeWeight(2);
stroke(255);
frameRate(30);
ySpeed = 4;
xSpeed = 10;
numberOfStars = 500;
// initialise each vertex to be the middle of the display
vertexCoords = new float[numberOfStars][4];
for (int i = 0; i < numberOfStars; i++) {
createCoords(i);
}
}
void draw() {
// clear the screen by resetting the background
background(0);
// for every vertex
for (int i = 0; i < numberOfStars; i++) {
if (hasLeftScreen(i)) {
// reset
createCoords(i);
}
// begin drawing the shape
beginShape();
// draw the vertex at the coordinates
vertex(vertexCoords[i][0], vertexCoords[i][1]);
// to coordinates nearer the centre to give the illusion of movement
vertex(vertexCoords[i][0] + (vertexCoords[i][2] * 5), vertexCoords[i][1] + (vertexCoords[i][3] * 5));
endShape();
// draw the point at the coordinates - this will give a 'classic' starfield simulation
//point(vertexCoords[i][0], vertexCoords[i][1]);
vertexCoords[i][0] = vertexCoords[i][0] + vertexCoords[i][2];
vertexCoords[i][1] = vertexCoords[i][1] + vertexCoords[i][3];
}
}
/**
* Work out of the vertex has left the screen
*
* @param vertexIndex the index of the vertex
* @return true if the vertex has left the screen
*/
boolean hasLeftScreen(int vertexIndex) {
// return true if the vertex has reached the top, the bottom or either side of the screen
return vertexCoords[vertexIndex][0] >= width
|| vertexCoords[vertexIndex][0] <= -width
|| vertexCoords[vertexIndex][1] >= height
|| vertexCoords[vertexIndex][1] <= -height;
}
/**
* Create the coordinates for the given vertex index number
*
* @param vertexIndex the index number of the vertex
*/
void createCoords(int vertexIndex) {
// create a random direction for the star
float xDirection = random(-xSpeed, xSpeed);
float yDirection = random(-ySpeed, ySpeed);
//create the coordinates as an array consisting of:
//0 - current x coordinate
//1 - current y coordinate
//2 - direction of the x coordinate
//3 - direction of the y coordinate
vertexCoords[vertexIndex] = new float[] {
(width / 2) + xDirection,
(height / 2) + yDirection,
xDirection,
yDirection};
}
No comments:
Post a Comment