I've an array that consists of many objects (called drops) and another separate object (called greenDrop). I would like to compare 2 objects at one time, one from the array & the other will be the separate object. To set an array and a separate object as method parameters, code as follows:
public boolean collision (GreenDrop gd1, Drop [] gd2){
for(int i=0;i<numDrops;i++)
{
int xDistBetwnDrops=gd1.xpos-gd2[i].xpos;
int yDistBetwnDrops=gd1.ypos-gd2[i].ypos;
int totalLengthOfDrops=(gd1.xpos+gd1.size)+(gd2[i].xpos+gd2[i].size);
if(xDistBetwnDrops<(totalLengthOfDrops/2)&&yDistBetwnDrops<(totalLengthOfDrops/2))
{
return true;
}
}
return false;
}
I was wondering if it is possible to set an element of the array in the method parameter instead of using the entire array? This is so that I won't have to include the for loop in my method. Calling the method in the main method will then be as follows:
if(collision(greenDrop, drops[i])==true)
The second parameter of the method can be changed as just Drop
public boolean collision (GreenDrop gd1, Drop gd2){
...
//The code has to be changed to not loop (Just compare two objects)
}
But if you still want to use collision
passing an array of Drop
(from elsewhere), then you can use varargs
public boolean collision (GreenDrop gd1, Drop... gd2){
...
}
You can pass zero, one element or multiple (Drop) objects like
collision(greenDrop)
collision(greenDrop, drops[i])
collision(greenDrop, drops[i], drops[j])
I don't know from where numDrops
is obtained. You might need to change that to gd2.length