Unity獲取鼠標點擊位置,物體朝鼠標點擊處移動


大型游戲中經常會有這種場景,點擊屏幕位置,人物就會朝着鼠標點擊位置移動,下面我們就來實現這種效果。

首先,我們在場景中添加一個Plane,並且設置它的tag為Plane,然后,在Plane上面添加一個Cube,設置好位置,剛好放置在Plane上面,最后,給cube添加一個腳本,腳本內容如下:

using UnityEngine;
using System.Collections;

public class RayCastTest : MonoBehaviour {
    //cube移動速度
    public float speed = 3f;
    private Vector3 offsetVec;
	
	// Update is called once per frame
	void Update () {
        RaycastHit hitInfo;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hitInfo, 100))
        {
            //當射線碰撞到plane並且鼠標左鍵按下時
            if(hitInfo.transform.tag == "Plane" && Input.GetMouseButtonDown(0))
            {
                //讓cube方向朝向點擊位置
                transform.LookAt(hitInfo.point);
                offsetVec = hitInfo.point - transform.position;
            }
        }
        //向量的magnitude表示這個向量的長度,當cube離我們點擊位置小於1的時候才停止移動,這個數值可以自己調節
        if(offsetVec.magnitude > 1f)
        {
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
            //更新offsetVec的值
            offsetVec = hitInfo.point - transform.position;
        }
	}
}

 運行的時候可能會出現一些bug,比如說cube往前移動的時候,坐標會逐漸往下偏移,這種現象是因為點擊位置的坐標比cube坐標偏下,獲取到點擊位置坐標的時候修改一下Y軸大小可消除這個bug。


免責聲明!

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



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