- Home /
AI cannot find closest Target
Hello Everyone, I have a fox that attacks humans when they are too close, but the problem is, it will only attack the one gameobject I assign it too. I want the game to be multiplayer, so I want it to attack anything with the tag "Player" when it gets too close. The script I made seems to have problems assigning the closest target. Could anyone explain to me what I am doing wrong. I greatly appreciate your help.
Here is my script.
var Target : Transform;
var Distance;
var LookatDistance = 25.0;
var ChaseRange = 15.0;
var AttackRange = 2.0;
var MoveSpeed = 5.0;
var Damping = 6.0;
var AttackRepeatTime = 1;
var moveSpeedCalm = 0.2;
var ChaseRangeCalm = 0.5;
var LookatDistanceCalm = 0.7;
var isAngry: foxWalkScript;
var MonsterAttack = 25;
private var AttackTime : float;
var controller : CharacterController;
var Gravity : float = 20.0;
private var MoveDirection : Vector3 = Vector3.zero;
function Start ()
{
AttackTime = Time.time;
}
function Update ()
{
Distance = Vector3.Distance(Target.position, transform.position);
if (Distance > LookatDistance)
{
isAngry.provoked =false;
}
if (Distance < LookatDistance)
{
LookAt();
}
if (Distance < AttackRange)
{
Attack ();
isAngry.provoked =true;
}
else if (Distance < ChaseRange)
{
chase ();
isAngry.provoked =true;
}
//////////////////
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
if (Physics.Raycast (transform.position, direction, hit, 20))
{
Debug.DrawLine (transform.position, hit.point, Color.yellow);
}
/////////////////
}
function LookAt ()
{
Target = GameObject.FindGameObjectWithTag("player").transform;
yield WaitForSeconds(0.1);
var rotation = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
}
function chase ()
{
moveDirection = transform.forward;
moveDirection *= MoveSpeed;
moveDirection.y -= Gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
function Attack ()
{
if (Time.time > AttackTime)
{
Target.SendMessage("ApplyDamage", MonsterAttack );
Debug.Log ("Insert Attack Here");
AttackTime = Time.time + AttackRepeatTime;
}
}
function ApplyDamage ()
{
if (isAngry.provoked == true)
{
ChaseRange = 4;
MoveSpeed = 2;
LookatDistance = 4;
}
}
Its suppose to assign the target at the LookAt function, but doesn't want to...
Your answer
![](https://koobas.hobune.stream/wayback/20220613153916im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Is FindGameObjectWithTag() too heavy on resources for 50 objects? 0 Answers
How to import the object from server to unity 2 Answers
Material doesn't have a color property '_Color' 4 Answers
Setting Scroll View Width GUILayout 1 Answer