簡體   English   中英

我無法統一繪制 lineRenderer

[英]i cant draw a lineRenderer in unity

我已經嘗試了幾個小時讓我的炮塔發射激光。 (炮塔在 0,0,0。)

到目前為止,這是我的代碼。 (這使炮塔點並在單擊時繪制線)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtMouse : MonoBehaviour
{

    [SerializeField]

    private LineRenderer lineRenderer;
    private Transform _turretBarrel;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Ray rayOrigin = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;

        if (Physics.Raycast(rayOrigin, out hitInfo))
        {
            if (hitInfo.collider != null)
            {
                Vector3 direction = hitInfo.point - _turretBarrel.position;
                _turretBarrel.rotation = Quaternion.LookRotation(direction);
                if (Input.GetKeyDown(KeyCode.Mouse0))
                {
                    //draw line from turret position to hitInfo.point
                    Debug.Log(hitInfo);
                    lineRenderer.SetPosition(0, hitInfo.point);
                }
            }



        }
    }
}
  1. 據我所知,您只是設置了一個點。 要繪制線條,您必須在每次更新時至少調用SetPosition兩次。 可能在炮塔位置 (0,0,0) 一次,然后像您目前所做的那樣在命中位置一次。
  2. 不是 100% 確定,但您可能需要將碰撞檢查與繪圖分開。 您將光線投射正確地放在 FixedUpdate 中(因為它與物理相關),但與繪圖相關的事情應該在正常的Update()函數中(因為每次重繪屏幕時都會調用該函數)。 因此,將位置保存在current_target類的變量中,並在Update()繪制 0 和該目標之間的線。

也許您忘記設置lineRenderer.positionCount 此外,您至少需要兩個點來畫一條線。

您可以嘗試以下代碼,我評論了更改。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtMouse : MonoBehaviour
{
    [SerializeField] private LineRenderer lineRenderer;
    private Transform _turretBarrel;

    void Start()
    {
        // must set position count, otherwise no line is drawn
        lineRenderer.positionCount = 2;

        // set first point to barrel position
        lineRenderer.SetPosition(0, _turretBarrel.position);
    }

    void FixedUpdate()
    {
        Ray rayOrigin = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;

        if (Physics.Raycast(rayOrigin, out hitInfo))
        {
            if (hitInfo.collider != null)
            {
                Vector3 direction = hitInfo.point - _turretBarrel.position;
                _turretBarrel.rotation = Quaternion.LookRotation(direction);
                if (Input.GetKeyDown(KeyCode.Mouse0))
                {
                    //draw line from turret position to hitInfo.point
                    Debug.Log(hitInfo);

                    // set second point to hit position
                    lineRenderer.SetPosition(1, hitInfo.point);
                }
            }
        }
    }
}

暫無
暫無

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

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