Although this is rather simplistic and doesn’t require the code to be super-optimized, I really want to learn how to do this whole game scripting thing correctly and intend on adding a LOT more to this in the future to improve AI so I want to ensure that this is as proper and efficient as possible. The main thing that I am concerned about is the Mathf.Sqrt() function. Would it be better to do the math on finding square root manually?
BTW, the purpose of this script is to “alert” the enemy that the player is near and have it start chasing them.
Thanks in advance for any help given.
using UnityEngine;
using System.Collections;
public class EnemyActionScript : MonoBehaviour {
float a;
float b;
Transform enm;
Transform target;
public float moveSpeed = 3;
bool diff = false;
Vector3 pos;
Vector3 poss;
public float dist = 1.1f;
float dif;
//------------------------------Who is being tracked?-----------------------------------------------------
void Start () {
target = GameObject.FindWithTag("Player").transform;
enm = GameObject.FindWithTag("Enm").transform;
}
void Update () {
if (Input.GetKey("escape"))
Application.Quit();
//------------------------------Get them positions!-----------------------------------------
pos = target.transform.position;
poss = enm.transform.position;
a = ((pos.x - poss.x) * (pos.x - poss.x));
b = ((pos.z - poss.z) * (pos.z - poss.z));
dif = squroot(a, b);
//-----------------------Is player within range?----------------------------------------------
if (dif < dist){
diff = true;
}
if(diff == true){
transform.LookAt(target);
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}
}
//----------------------------------Compute square root (seperate function is there just in case I decide to do the math manually)-------------------------------------
float squroot(float a, float b){
float ret;
float carry;
carry = a + b;
ret = Mathf.Sqrt(carry);
return ret;
}
}