I want to add a sort of turret to my game, that, if an enemy is close enough, the turret will begin to shoot it. but while it’s shooting that one and another comes within range, i want it to stay on the same target. Is there any easy way to do this?
Well, it depends on how your target selection really works, but something like…
newTarget = getClosestTarget();
if(currentTarget == null) {
currentTarget = newTarget;
}
Should work.
Make it check to see if its target is still in range and still exists. If not, find the next target.
if(target==null||getDistance(x, y, target.x, target.y)>range) {
target = getNextTarget()
}
[EDIT] It needs to be greater than, not less than. :
How I would do this is have a boolean lookingForTarget which is set to false when the turret is shooting at some thing already. So something like:
public class Turret {
private float radius = 15; // Set this to whatever your radius is
private boolean lookingForTarget = true;
private Guy target = null;
... // Other vars
public update(ArrayList<Guy> guys) {
if(lookingForTarget) {
for(Guy g: guys) {
if(distanceFromMeToAGuy(g) < raduis) {
target = g;
lookingForTarget = false;
break; // In case more than one guy entered the raduis this update
// just select the first one, you could also
// prioritize by HP remaining, or whatever you like
}
}
if(!lookingForTarget) {
attack(target);
if(target.isDead()) {
target = null;
lookingForTarget = true;
}
}
}
... // more methods here
}
}
Okay so I see that while I was typing all this out others have replied, but I figured I’d post it anyway because whatever!
There’re many way to do this, as sugessted above. How about your searching method, it works every loop or just when enemy comes or what?