HI
I’m having problem with understanding this array
I have four pictures loaded, but when i open it only 3 of them shows
I also want to add some extra pictures in the array, but it wont let me.
In the console it shows this: ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
The code is a drag and drop, where i should be able to move the pictures around
boolean hold = false; // Determines if an image is being dragged (initially false)
int selected = -1; // Holds the index of the selected image (-1 means none selected)
PImage[] hand_images = new PImage[4]; // Array to store PImage objects (holds 4 images)
float[] x = {100, 300, 600, 800}; // X-coordinates for the images
float[] y = {100, 200, 300, 400}; // Y-coordinates for the images
void setup() {
size(764, 990); // Set canvas size
// Load images into the array
hand_images[0] = loadImage("10.png");
hand_images[1] = loadImage("11.png");
hand_images[2] = loadImage("12.png");
hand_images[3] = loadImage("13.png");
}
void draw() {
background(255); // Set background color
// Display images and handle dragging if necessary
int i = 0;
for (PImage pg : hand_images) {
if (i == selected && hold) {
fill(0, 0, 0); // Color for a marker if an image is selected
rect(x[i] - 5, y[i] - 5, 5, 5); // Draw a marker around the selected image
}
image(pg, x[i], y[i]); // Display the image at its designated position
i++;
}
// If an image is selected and being dragged, update its position
if (hold && selected >= 0) {
x[selected] += (mouseX - pmouseX);
y[selected] += (mouseY - pmouseY);
}
}
void mouseClicked() {
hold = false; // No image is being dragged on mouse click
// Check if mouse click is within an image's boundary
int i = 0;
for (PImage pg : hand_images) {
if (mouseX > x[i] && mouseX < x[i] + pg.width &&
mouseY > y[i] && mouseY < y[i] + pg.height) {
hand_images[i] = hand_images[0]; // Replace clicked image with the first image in the array
return; // Exit the function
}
i++;
}
}
void mousePressed() {
// Check if mouse press occurs within an image's boundary to select it for dragging
int i = 0;
for (PImage pg : hand_images) {
if (mouseX > x[i] && mouseX < x[i] + pg.width &&
mouseY > y[i] && mouseY < y[i] + pg.height) {
selected = i; // Set the selected index
hold = true; // Indicate an image is being dragged
return; // Exit the function
}
i++;
}
}
void mouseReleased() {
hold = false; // No image is being dragged on mouse release
}