Hi everyone , i was writing an ai and i had some problems. Let me explain like that ;
I have 2 A Characters . And i’m writing ai for them.
Their enemies are for example 4 B characters.
Now , i want A characters to select randomly one of the B characters and go near them. I wrote a code like that ;
var Target : Transform;
var Range = 10.0;
function Awake ()
{
Target = GameObject.FindWithTag("Enemy").transform; // This indicates what is our target , and if i don't add this line , A characters do nothin' .
}
function Update ()
{
if (Target Follow())
{
var TargetRotation = Quaternion.LookRotation(Target.position - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, TargetRotation , Time.deltaTime * 2.0);
}
}
function Follow()
{
if(Vector3.Distance(transform.position, Target.position) > Range ) // if target is out of range
{
print("too far"); // say too far
return false;
}
if (Vector3.Distance(transform.position, Target.position ) < Range ) // if target is in range
{
transform.Translate(Vector3.forward * Time.deltaTime); // it follows us
}
if (Vector3.Distance(transform.position,Target.position) < 5 ) // if it's too close
{
Attack(); // it attacks
}
// nothing about the thing which i want over here ,the lines below just for making ai smarter ( i'm using it for detect the objects between the character and target )
var hit : RaycastHit;
if(Physics.Linecast(transform.position, Target.position,hit))
{
if (hit.collider.gameObject.tag !="Player")
{
print("Arada bu var: "+hit.collider.gameObject.name);
}
else
{
print("Liseli detected");
return true;
}
}
return true;
}
function Saldiri()
{
}
But when i launch game , A characters detect one of the B characters and both of the A characters attack on him. But always they attack on the same character. So please help me , i want them to attack one of the characters in their range.
I also read sumthin’ about Random.Range , but i just couldn’t know how to use it in :
this . But in the code you’ve given me , we make another variable called targets , so the code is not workin’ because the continuing part of the code is depending on Target variable .
Your “targets” variable is an array of GameObjects with the “Enemy” tag. You use it as a list of enemies, and use your random number generator to select one of them, which becomes Target.