1. 程式人生 > >Unity射線&自動尋路/右鍵點選某一點會使物體跟隨至滑鼠點選位置/計算目標物體距離滑鼠點選位置的距離

Unity射線&自動尋路/右鍵點選某一點會使物體跟隨至滑鼠點選位置/計算目標物體距離滑鼠點選位置的距離

public class MyRay : MonoBehaviour {

public GameObject GameObject;//要例項化的物體 粒子特效

public GameObject Player;

// private Animation ani;

private NavMeshAgent Agent;
private float distance;

void Start ()
{
   Agent=   Player.GetComponent<NavMeshAgent>();
  //  ani = Player.GetComponent<Animation>();
}

// Update is called once per frame
void Update () {

    if (Input.GetMouseButtonDown(1))
    {
        //得到射線
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        //進行物理檢測
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 1000))
        {
            Debug.DrawLine(ray.origin, hit.point, Color.blue, 0.5f);
            //例項化特效 先定義特效物體
            Instantiate(GameObject, hit.point, Quaternion.identity);
            //改變材質顏色
       //     hit.collider.gameObject.GetComponent<Renderer>().material.color = Color.green;
            Agent.destination = hit.point;//把自動追蹤的目標位置設定為碰撞點point

         //   ani.CrossFade("Battle_Run");
        }
    }
//計算距離

// distance = Agent.destination - Player.transform.position;
distance= Vector3.Distance(Agent.destination ,Player.transform.position);