I'm trying to write code to determine if an enemy hears a 'gunshot'. I figured I could use getObjectsInRange with the actor I use for a gunFlash.
This is what I have:
When I try to run I get this error:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to GunFlash
at Enemy.hearShot(Enemy.java:100)
at Enemy.stateOfBehaviour(Enemy.java:293)
at Enemy.act(Enemy.java:75)
at greenfoot.core.Simulation.actActor(Simulation.java:565)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:523)
at greenfoot.core.Simulation.runContent(Simulation.java:213)
at greenfoot.core.Simulation.run(Simulation.java:203)
So I guess the problem is that it's returning a list and I just want the one actor.
How can I adapt this to make it work?
Or is there anything I could use alternatively?
It would be nice if there was a way to detect nearby objects like the getOneIntersectingObject and getOneObjectAtOffset methods, but they don't really cover areas :/
(Just had an idea as I wrote that: what if I create an actor that is just a massive invisible box and use getOneIntersectingObject... would that work?)
private boolean hearShot() { heardShot = (GunFlash) getObjectsInRange(1200, GunFlash.class); return heardShot != null; }
if (!canSeePlayer() && hearShot()) { lastSeen.set(heardShot.x, heardShot.y); setState(chasing); }