Enemy Attacking Even When Not In Range
So I have this small enemy AI (look at the player and follow him if in range) but the only problem is the "if in range" part seems to be irrelevant!
Here's my script:
#pragma strict
var Player : Transform;
var MoveSpeed = 5;
var MaxDist = 7;
var MinDist = 6;
var AttackDistance = 5;
var PlayerHealth = 100;
function Start ()
{
}
function Update ()
{
transform.LookAt(Player);
transform.position += transform.forward*MoveSpeed*Time.deltaTime;
if(Vector3.Distance(transform.position,Player.position) <= AttackDistance);
{
PlayerHealth = PlayerHealth - 0.000001;
print(PlayerHealth);
}
if(PlayerHealth <= 0) {
Application.LoadLevel(1);
}
}
Answer by bubzy · Feb 02, 2017 at 09:28 AM
if(Vector3.Distance(transform.position,Player.position) <= AttackDistance) >;< THIS!!!!!
you ended the statement with that semicolon :), remove it
if(Vector3.Distance(transform.position,Player.position) <= AttackDistance)
Answer by HenryStrattonFW · Feb 02, 2017 at 09:33 AM
I would imagine this is because your movement code is just inside your update, meaning the movement code is not bound to any "too close / too far" logic at all. Try something like this.
function Update ()
{
// Rotate to face player.
transform.LookAt(Player);
if(Vector3.Distance(transform.position,Player.position) <= AttackDistance);
{
// Player within range. damage player.
PlayerHealth = PlayerHealth - 0.000001;
print(PlayerHealth);
// Only need to check player health here as this is where it is decreased.
if(PlayerHealth <= 0)
{
Application.LoadLevel(1);
}
}
else
{
// Too far away, move towards player.
transform.position += transform.forward*MoveSpeed*Time.deltaTime;
}
}
I've added an else to your distance check so that if the player is not within range that will then trigger the movement logic. Additionally I moved the health check to where the health is decreased. It's a minor optimization so feel free to ignore that part, the important part is the else, and the movement of the transform.position change into it.
Your answer
Follow this Question
Related Questions
Add GameObject Raycast hits to a variable 1 Answer
Variable not being assigned 0 Answers
Cannot properly access player position 1 Answer
How to get the position of a gameObject based on its index in an array? 0 Answers
If you want to destroy the game object, please call 'Destroy' on the game object instead. 1 Answer