Hi all,
Here's a problem that's been bugging me for a few days now; I couldn't figure it out on my own, so I thought I'd ask here. I've just started making a Tower Defense game, and have quickly set up a couple temporary scripts, one attached to a cube that automatically moves in a straight line past my tower, and one on my tower. A child of the tower is a cylinder collider made into a trigger.
At first I tried making the trigger itself note when the cube entered its range, but since I couldn't figure that out, I made the cube send a message to the tower when the cube hit the trigger, and from there made the tower look at the cube until it left the trigger area. That worked fine, until I added in multiple cubes. The way I had set it up meant it screwed up when there were multiple cubes in the trigger area, but I can't for the life of me figure out how to make it so that:
- The first cube is targeted by the tower,
- When that cube leaves the trigger area or is destroyed, the tower targets the next one, and
- Continues to cycle through all of the possible targets when the current one is destroyed or goes out of range
Here's the scripts I already have, if it helps in any way. This one's on the turret:
var targetedEnemy : GameObject;
var inRange : boolean = false;
function Update()
{
if (targetedEnemy && inRange == true)
{
transform.LookAt(targetedEnemy.transform);
}
}
function EnteringRange(recievedGameObject : GameObject)
{
targetedEnemy = recievedGameObject;
inRange = true;
}
function LeavingRange()
{
inRange = false;
}
And this one's on the cube:
var thisObject : GameObject;
var otherObject : GameObject;
function Start()
{
thisObject = gameObject;
}
function Update ()
{
transform.Translate(0.025, 0, 0);
}
function OnTriggerEnter (hit : Collider)
{
otherObject = hit.gameObject;
otherObject.SendMessageUpwards("EnteringRange", thisObject);
}
function OnTriggerExit (hit : Collider)
{
otherObject.SendMessageUpwards("LeavingRange");
}
Thanks for your help!
Update:
I tried changing the inRange variable to an int, and every time an enemy came in range it'd add 1 to the variable, and every time one left it'd subtract 1, which made it not screw up, however the turret would then target the newest enemy to enter the range, whereas I wanted it to select the first one to enter, i.e the one closest to leaving.
Well, that was just an existing example ;) You don't need all that things. If you really plan to implement all these modes your enemies have to track some information: creation time for oldest and newest, health for strongest and weakest,if you have slow towers the current speed for fastest and slowest and maybe the way it has traveled to determine which one is furthest.
– Bunny83Every enemy should have a script that holds this information (i call it "Enemy.js"). You can simply get the script reference with
– Bunny83var enemy : Enemy = currentCollider.GetComponent.<Enemy>();. I will add it to my example.