Sword Combat System: Detect if player in range

Ok, guys, I’ve been Googling, testing, and experimenting for the past 2 hours.

I have a first person character with a sword. I need him to attack the enemies and give them damage. I’m hitting a hiccup in that I can’t figure out how to detect if the enemy is in range.

I think this is how I want the system to work: I have a box collider in front of my main character. I want the box to check every frame whether or not an enemy is touching the box. If there is an object with the tag “enemy” in the box, I want a boolean variable to be true, and if there is no enemy in the box, then I want the variable to be false. Right now, I can get the variable to be true when the box collides with the enemy, but I can’t seem to get it to change to false.

var enemyInRange : boolean = false;

function OnTriggerEnter (other : Collider) 
{
	if(other.gameObject.tag == "enemy")
	{
		enemyInRange = true;
	}
}

function OnTriggerExit (other : Collider)
{
	if(other.gameObject.tag == "enemy")
	{
		enemyInRange = false;
	}
}

function Update()
{
   // Tells me what the value of the variable is, so that I can see if it changes
   Debug.Log(enemyInRange);
}

Thanks for the help!!!

You should probably not use true and false but rather use a count of enemies or else two can enter, one can exit and you’ll be set to false.

So, make enemyInRange in to enemyInRangeCount and an int type.

Increase on Enter, decrease on Exit.

If you’re keeping the box collider system, I agree with @Dracorat, but I wonder about how you have your game play mechanics set up.

If you have a targeting system, i.e before I attack, I need to have selected a target. In which case, you have the target so do a Vector3.Distance check between player and target to get the distance and compare against some range value. I think this is simply and accurate.

If you don’t have a targeting system, then shouldn’t your character be able to swing regardless of anything around him? If he hits (meaning the collider on the weapon hits a collider on a enemy) an enemy, great—Bully for him; If he doesn’t…no big deal right? The point is here “range” doesn’t matter since it’s tethered by the model of the weapon.

I just want to make sure we’re solving a problem you actually have is all :wink: