簡體   English   中英

用鼠標移動 Object 取決於它的旋轉 Unity3D

[英]Move Object with mouse depending on its rotation Unity3D

我正在使用下面的腳本通過鼠標移動平滑地移動 object(在 X 和 Z 軸上),它在世界軸上完美運行,我的意思是當對象的旋轉為 (0,0,0) 時。

但是如何使 object 在其局部軸上移動(我的意思是當它的 X 旋轉為 -20 時,它的 Z 移動應該是漸進的)?

腳本:

private Vector3 screenPoint;
private Vector3 offset;

// Update is called once per frame
void Update () {

    if (Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        screenPoint = Camera.main.WorldToScreenPoint(transform.position);

        offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    if (Input.GetMouseButton(0) && !Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

        Vector3 curPosition = new Vector3((Camera.main.ScreenToWorldPoint(curScreenPoint).x + offset.x), 2, (Camera.main.ScreenToWorldPoint(curScreenPoint).z + offset.z));

        float newX = Mathf.Clamp(curPosition.x, -3f, 3f);
        float newZ = Mathf.Clamp(curPosition.z, -6f, 1.5f);

        transform.position = Vector3.Lerp(transform.position, new Vector3(newX, transform.position.y, newZ), 10 * Time.deltaTime);
    }
}

好吧,我找到了答案,而且很簡單:

  • 創建一個空的游戲對象並使其成為移動 object 的父對象。
  • 將旋轉應用於父級,因此子級沒有旋轉。
  • 將代碼附加到孩子身上,但使用“transform.localposition”而不是“transform.position”。

暫無
暫無

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

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