通過射線讓物件移動

彭然心跳發表於2017-10-09
using UnityEngine;
using System.Collections;

public class RayScript2 : MonoBehaviour {
    Vector3 _Taget;
    bool _isMove=true;//移動是否結束
    public float speed=1f;
  

    void Start() {

    }

    void Update () {

        if (Input.GetMouseButtonDown(1))//移動
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "Dimian")
                {
                    _Taget = hit.point;
                    _Taget.y = 0.5f;
                    _isMove = false;//現在又有新的目標了繼續移動吧!
                }

            }
        }
        Move(_Taget);
    }



    void Move(Vector3 _Tar) {
        if (!_isMove) {
            Vector3 v1 = _Tar - transform.position;
            transform.position += v1.normalized * speed * Time.deltaTime;
            transform.LookAt(_Tar);
            if (Vector3.Distance(_Tar, transform.position)<0.3f) {
                transform.position = _Tar;
                _isMove = true;
            }
        }
    }

    
}

 

相關文章