[英]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);
}
}
}
}
}
SetPosition
兩次。 可能在炮塔位置 (0,0,0) 一次,然后像您目前所做的那樣在命中位置一次。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.