簡體   English   中英

Unity-嘗試將多維數據集移動到鼠標位置-多維數據集向錯誤的方向移動

[英]Unity - Trying to move cube to mouse position - cube moves in wrong direction

我正在嘗試制作一個簡單的游戲,當玩家按下鼠標按鈕時,立方體會追逐鼠標。

到目前為止,這是我的代碼:

public class PlayerCubeController : MonoBehaviour {

    public float speed = 1.0f;
    Vector3 targetPos = new Vector3();

    void Start () {
        speed = speed * 0.01f;
    }

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            Debug.Log (Input.mousePosition);
            targetPos = Input.mousePosition;
            targetPos.z = 0;

        } else if (Input.GetMouseButtonUp (0)) {
            targetPos = transform.position;
        }

        transform.position = Vector3.Lerp (transform.position, targetPos, speed * Time.deltaTime);
    }
}

不幸的是,立方體永遠不會朝着鼠標的方向移動。 我可以將鼠標放在屏幕的左下角,但多維數據集仍將移到右上角。

奇怪的是,如果將鼠標放在屏幕的左側,則多維數據集將直線上升。

誰能告訴我我哪里出問題了?

您的問題很簡單: Input.mousePosition定義鼠標在屏幕坐標中的位置(例如,從(0,0)到(1920,1080))。 如果要從鼠標位置獲取3d點,則需要執行其他步驟。 我看到兩種可能性:


使用Camera.main.ScreenToWorldPoint並手動指定您想要的距離相機:

 var v = Input.mousePosition;
 v.z = 10.0;
 v = Camera.main.ScreenToWorldPoint(v);
 // Move your cube to v

文檔: https : //docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html


或使用光線投射,例如使用Camera.main.ScreenPointToRay來獲取地面上的點:

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, 100))
        // Move your cube to hit.point

文檔: https : //docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html

簡而言之,您需要將屏幕坐標轉換為世界坐標。 這是一個例子

https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

類似於以下內容:

 Vector3 mouseP = Input.mousePosition;
 mouseP.z = 10.0;
 Vector3 worldP = Camera.main.ScreenToWorldPoint(mouseP);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM