Unfortunately I’m going to have to bring this back up with somewhat the same issue. Right now, performance is fine, and the code works more or less. One thing that does not however work is the maximum distance the raycast travels.
function AllocateTarget() {
if (Time.time - nullifyRate > nextNullifyTime)
nextNullifyTime = Time.time - Time.deltaTime;
// Keep firing until we used up the fire time
while( nextNullifyTime < Time.time)
{
var targets = GameObject.FindGameObjectsWithTag ("Support");
foundTarget = false;
for (var other in targets) {
if (Physics.Raycast (transform.position, other.transform.position, 150)) {
if (other.tag == "Support") {
foundTarget = true;
//Debug.DrawLine(transform.position, Vector3(other.transform.position.x+Random.Range(-1,1),other.transform.position.y+Random.Range(-1,1),other.transform.position.z+Random.Range(-1,1)), Color.white);
targetPos = Vector3(other.transform.position.x+Random.Range(-1,1),other.transform.position.y+Random.Range(-1,1),other.transform.position.z+Random.Range(-1,1));
}
}
}
nextNullifyTime += nullifyRate;
}
}
Here I am going through a small list of what can be at the most 3 objects with the tag ‘Support’. I then go through each one and raycast to see if it is within a certain distance. If it is, then the position of that object is recorded in a variable for further use.
However, there is a problem. I’ll demonstrate with this scenario:
Object 1 is 50 meters away from the raycast origin.
Object 2 is 1000 meters away from the raycast origin.
Object 3 is also 1000 meters away from the raycast origin.
If the max raycast length is 100 meters, then object 1 is sighted and its position is recorded. However, object 2 and 3 are sometimes recorded as well, regardless of being out of range. If ALL objects are out of range then none are recorded.
Is this a bug or am I doing something wrong? I’ve gone over my code a few times and can’t solve this.
I’m aware that I am checking for the same tag twice, but there are problems if I don’t do this. I also use localPosition on the Z axis as I need to compensate for the speed of the object.