﻿using UnityEngine;
using System.Collections;
using System;

public class tapMove : MonoBehaviour {

	//AIの変数用
	UnityEngine.AI.NavMeshAgent agent;

	//hit情報（タップ先）情報の格納用
	RaycastHit hit;

	//タップ用レイの準備
	Ray ray;

	[SerializeField, HeaderAttribute ("circlePrefabをここにアサイン")]
	public GameObject circlePre;
	[SerializeField, HeaderAttribute ("タップできる最大距離")]
	public float rayLength;
	//レイヤーマスクでタップを監視するレイヤー設定用
	LayerMask mylayerMask;

	//アニメーターの変数用
	Animator animator;


    //
    public Transform target;
   // float speed = 0.2f; 

	//初期化
	void Start () {
		agent = GetComponent<UnityEngine.AI.NavMeshAgent>();//AIをこのスクリプトがあるゲームオブジェクトから探す
		animator = GetComponent<Animator> ();//このゲームオブジェクトからアニメーターを探す
		int layerMask = LayerMask.GetMask(new string[] {"Default"});//レイヤーマスクの設定
		mylayerMask = layerMask;//マスク用
	}


	//毎回処理します
	void Update () {


        // 左クリックしたときに、
        if (Input.GetMouseButtonDown(0))
        {
            // マウスの位置からRayを発射して、
            //Debug.Log("tes");
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            // 物体にあたったら、
            if (Physics.Raycast(ray, out hit, rayLength, mylayerMask))
            {
                // その場所に、Nav Mesh Agentをアタッチしたオブジェクトを移動させる
                agent.SetDestination(hit.point);

                Quaternion targetRotation = Quaternion.LookRotation(hit.point - transform.position);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime);
                // "walk"アニメーションに遷移
                animator.SetTrigger("swim");
                spawnPrefab();
            }


        }

		// 目的地とプレイヤーとの距離が1以下になったら、マーカーを消す
		if (Vector3.Distance(hit.point, transform.position) < 1.0f) {
            GameObject delobj =  GameObject.Find("circle");

            Destroy(GameObject.Find("circlePrefab"));
		}
	}

	//ターゲットマーカーを表示
	void spawnPrefab(){

		string delPreviusGO = circlePre.name;//Prefabの名前を取得する
		try{
		GameObject deathObj =  GameObject.Find (delPreviusGO);//Prefab名のゲームオブジェクトがあったら
			Destroy(deathObj);//それを消す＝つまり目的地に到着前にタップして行き先を変更した時用
		}catch(NullReferenceException e) {
			//見つからなかった時の処理
		}

		Vector3 mypos ;//行き先の座標設定用
		float myPosy = hit.point.y + 0.01f;//若干高い位置にマーカー表示させる
		mypos = new Vector3 (hit.point.x, myPosy, hit.point.z);//Yだけ少し高くした座標作成
		GameObject circleGO = Instantiate(circlePre, mypos, circlePre.transform.rotation) as GameObject;//Prefabを生成する
		circleGO.name = circlePre.name;//Prefabでなくゲームオブジェクトにして名前を設定する（上で名前で検索して消すために設定いている）

	}


}