unity3d 讓物體移動到點擊位置


using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {
    //在場景中鼠標點擊地面后,角色可以移動到目標位置

    private Vector3 target;
    private bool isOver = true;
    public float speed;
    void Start () {
    
    }
    
    void Update () {
        if(Input.GetMouseButtonDown(0))
        {
            print("MouseDown");
            //1. 獲取鼠標點擊位置
            //創建射線;從攝像機發射一條經過鼠標當前位置的射線
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //發射射線
            RaycastHit hitInfo = new RaycastHit();
            if (Physics.Raycast(ray, out hitInfo))
            {
                //獲取碰撞點的位置
                if (hitInfo.collider.name == "Plane")
                {
                    target = hitInfo.point;
                    target.y = 0.5f;
                    isOver = false;
                }
            }
            //RaycastHit[] hitAll = Physics.RaycastAll(ray, 1000);
            //foreach(RaycastHit hitInfo in hitAll)
            //{
            //    print(hitInfo.collider.name);
            //    if (hitInfo.collider.name == "Plane")
            //    {
            //        target = hitInfo.point;
            //        target.y = 0.5f;
            //        isOver = false;
            //    }
            //}
        }

        //2. 讓角色移動到目標位置
        MoveTo(target);
    }

    //讓角色移動到目標位置
    private void MoveTo(Vector3 tar)
    {
        if(!isOver)
        {
            Vector3 offSet = tar - transform.position;
            transform.position += offSet.normalized * speed * Time.deltaTime;
            if(Vector3.Distance(tar, transform.position)<0.5f)
            {
                isOver = true;
                transform.position = tar;
            }
        }

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM