Hello. Sorry for my English. I can not win Mathf.Clamp. I will randomly appear on the scene GameObject. This object I want to restrict the movement and use of Mathf.Clamp. It starts to move towards the player when the player is close to approaching the object. I want set the him a range of motion, and if it moves away from the starting point to 10.0f then stops. That’s only when you start the script object begins to frantically move within a predetermined range. How to fix it? =)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float xMax, xMin, zMax, zMin;
public float rangeClamp = 10f;
}
public class EnemyScript : MonoBehaviour {
public GameObject _Managers;
float randomX;
float randomZ;
float constY;
MeshRenderer enemyRender;
public Boundary boundary;
// Use this for initialization
void Start () {
enemyRender = gameObject.GetComponent<MeshRenderer> ();
enemyRender.enabled = false;
constY = gameObject.transform.position.y;
randomX = Random.Range (-50f, 50f);
randomZ = Random.Range (-50f, 50f);
transform.position = new Vector3 (randomX, constY, randomZ);
boundary.xMax = gameObject.transform.position.x + boundary.rangeClamp;
boundary.xMin = gameObject.transform.position.x - boundary.rangeClamp;
boundary.zMax = gameObject.transform.position.z + boundary.rangeClamp;
boundary.zMin = gameObject.transform.position.z - boundary.rangeClamp;
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
_Managers.GetComponent<EventHandler>().isPlayerEnemy = true;
_Managers.GetComponent<EventHandler>().isLeaveEnemy = true;
enemyRender.enabled = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
_Managers.GetComponent<EventHandler>().isPlayerEnemy = false;
_Managers.GetComponent<EventHandler>().isLeaveEnemy = false;
enemyRender.enabled = false;
}
}
void FixedUpdate ()
{
gameObject.transform.position = new Vector3
(
Mathf.Clamp (gameObject.transform.position.x, boundary.xMin, boundary.xMax),
0.5f,
Mathf.Clamp (gameObject.transform.position.z, boundary.zMin, boundary.zMax)
);
}
}