I am in the process of writing a program for a java mini-game. I need to determine if two objects collide. One of the object is just of type Player (one single object) with the name of player
and the other is part of an arrayList of object type Enemy with the name of the arrayList being enemies
. I know that I can use the intersect()
function because they both extend Rectangle. However, I am wondering what exactly the syntax of this statement would be? i.e. - player.intersect(enemies)
. However, this does not seem to be correct?
Asked
Active
Viewed 211 times
-3

Andrew Thompson
- 168,117
- 40
- 217
- 433

javainsanity1414
- 9
- 5
-
How is the `ArrayList` relevant? Why do you care where the `Enemy` came from? You (presumably) only care if it intersects with the `Player`. Please [edit] your question to show us what you're trying to do and what isn't working (an [mcve]). – Kevin J. Chase Mar 30 '17 at 02:38
1 Answers
3
Because enemies
is a list, you can't directly call intersect
on the list. What you can do instead is loop through the list:
static boolean anyEnemyCollides(Player player, List<Enemy> enemies) {
for (Enemy enemy : enemies) {
if (player.intersect(enemy)) {
return true;
}
}
return false;
}
Edit:
I should also mention that if you're using guava, you can do:
Iterables.any(enemies, (enemy) -> player.intersect(enemy));

muzzlator
- 742
- 4
- 10