Arrays - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki
Last week we created a game with a single target. But what if there are multiple targets?
We use arrays to store multiple pieces of information.
In JavaScript we declare arrays using square brackets, []. We can define an empty array:
var targets = [];
or we can provide initial values:
var targets = [1, 2, 3, 4, 5];
Arrays can contain any type of value including strings:
var targets = ["star", "moon", "galaxy", "jupiter"];
We can use two arrays, one for each axis:
var targetX = [20, 40, 50, 5];
var targetY = [300, 200, 300, 5];
Our program will need to interpret corresponding locations in the array as belonging to the same target. For example the second target will have the co-ordinates (40, 200).
We can access arrays by the array index. Like pixel co-ordinates, array indices start at 0. So targetX[0] will be 20 and targetY[0] will be 300.
We can treat array elements like a normal variable, and hence we can change the value. If we want to assign a new random location to target at index 3:
targetX[3] = random(width);
targetY[3] = random(height);