簡體   English   中英

基於鼠標瞄准Unity3d

[英]Mouse based aiming Unity3d

我正在制作炮彈射擊游戲。 這是一個簡短的代碼,我在計算瞄准方向。

            Vector3 mousePos = Input.mousePosition;
            mousePos.z = thisTransform.position.z - camTransform.position.z;
            mousePos = mainCamera.ScreenToWorldPoint (mousePos);

            Vector3 force = mousePos - thisTransform.position;
            force.z = force.magnitude;

這適用於球和角度(0,0,0)。 但是當角度改變時,我無法向正確的方向射擊。

假設球和相機都在右側看45度,相同的代碼不起作用。

當前代碼假定兩者都處於角度(0,0,0)。 所以在上面提到的情況下,投擲方向總是錯誤的。

我想把球扔向任何方向。 但假設它為0角並相應地投擲。

在這種情況下使用Camera.ScreenToWorldPoint是錯誤的。

你應該對飛機使用光線投射。 這是一個沒有不必要數學的演示:

光線投射鼠標在飛機上的位置

Raycasting為您提供了優勢,您無需猜測用戶點擊的“深度”( z坐標)。

這是上面的簡單實現:

/// <summary>
/// Gets the 3D position of where the mouse cursor is pointing on a 3D plane that is
/// on the axis of front/back and up/down of this transform.
/// Throws an UnityException when the mouse is not pointing towards the plane.
/// </summary>
/// <returns>The 3d mouse position</returns>
Vector3 GetMousePositionInPlaneOfLauncher () {
    Plane p = new Plane(transform.right, transform.position);
    Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
    float d;
    if(p.Raycast(r, out d)) {
        Vector3 v = r.GetPoint(d);
        return v;
    }

    throw new UnityException("Mouse position ray not intersecting launcher plane");
}

Demonstation: https//github.com/chanibal/Very-Generic-Missle-Command

暫無
暫無

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

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