We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi everyone, I have a problem with my project. I want to add more boxes into my project by mousePressed function.
Box[] boxes=new Box[5];
void setup(){
size(200,200);
rectMode(CENTER);
for(int i=0;i<boxes.length;i++){
boxes[i]= new Box( random(100),random(100), random(5,15)
);
}
}
void draw(){
background(192);
for(int i=0;i<boxes.length;i++){
boxes[i].draw();
}
for(int j=0;j<boxes.length;j++){
for(int k=0; k< boxes.length; k++){
if(j !=k){
boxes[j].attract(boxes[k]);
}
}
}
}
void mousePressed(){
for(int i=0;i<boxes.length;i++){
boxes[i].mousePressed();
}
}
Answers
code is unreadable
edit post, highlight code, press ctrl-o
mousePressed needs to add a new Box, the same way it did with the first 5 in setup()
but first you'll have to increase the size of the array.
but tbh, you'd be better off with an ArrayList than with a Box[].
you are also missing the Box class.
this is my Box Classes:
But i can not increase the number of box. I tried to do :
but it did not work.... Can you help me?
line 2 initialises the size of the array to the current value of num, set in line 1. changing num later won't change the size of the array.
there is a method to expand an array, it's in the reference. it is, however, terrible - arrays aren't meant to be extended. which is why i suggested using an ArrayList.
Can you explain for me? How to apply array list in this? I am quite confused now :(
becomes
so that's a new ArrayList full of things of type Box. note that it doesn't have a limit to how big it can be, it can handle more than 5.
instead of setting array entries to be new Box you add() them so
becomes
you can do this as many times as you like, ie within your mousePressed() method.
and accessing them is not
boxes[i]
butboxes.get(i)
;https://forum.processing.org/two/discussion/8080/why-use-arraylist-instead-of-array-with-append
I tried , but when we change it , we will not use i, will we ?
...
but if all you're using i for is to iterate over all the boxes then you don't need it and can use
To be honest, Have you tested it? although I tried many times and following your induction, It does not work
Implementing @koogs suggestions:
Kf
thank you very very much kfrajer , it is fantastic :D