퍼온 자료

Unity 유니티 라인그리기, LineRenderer

ITSkeleton 2020. 6. 18. 11:43
728x90
반응형

라인 렌더러

Line Renderer는 3D 공간에서 두 개 이상의 점의 배열을 가지고 각각의 사이에 직선을 그립니다. 따라서, 하나의 라인 렌더러 컴포넌트를 사용하여 1개의 직선에서 복잡한 나선형까지 그릴 수 있습니다. 선은 반드시 연속적인 상태로 되어 있습니다. 2개 이상의 완전히 별도의 라인을 그리려면, 각각 자신의 라인 렌더러를 가진 여러 GameObject를 사용해야 합니다.

라인 렌더러는 1픽셀의 가는 선은 렌더링하지 않습니다. 폭이 있고, 텍스처를 붙일 수 있는 빌보드 선을 렌더링합니다. Trail Renderer와 같은 라인 렌더링용 알고리즘을 사용합니다.

프로퍼티

프로퍼티:기능:

Materials 이 목록의 첫 번째 메테리얼이 선을 렌더링하는 데 사용됩니다.
Positions 연결할 Vector3 점의 배열.
        Size 이 선에서의 세그먼트의 수.
Parameters 각 선에 대한 파라미터 목록 :
        StartWidth 첫 번째 선의 위치에서의 폭.
        EndWidth 마지막 선의 위치에서의 폭.
        Start Color Color at the first line position. Note: This has no effect unless the attached material uses a vertex shader.
        End Color Color at the last line position. Note: This has no effect unless the attached material uses a vertex shader.
Use World Space 활성화하면 오브젝트의 위치가 무시되고, 선이 월드의 원점 주변에서 렌더링됩니다.

세부정보

라인 렌더러를 만들려면 다음 단계를 수행합니다.

  1. GameObject->Create Empty를 선택한다.
  2. Component->Effects->Line Renderer를 선택한다.
  3. 라인 렌더러에 텍스처 또는 Material을 드래그 합니다. 메테리얼 파티클 쉐이더를 사용하는 데 이상적입니다.

  • 라인 렌더러는 하나의 프레임에 모든 정점을 배치할 필요가 있는 경우의 효과로 사용하기에 적합합니다. *이 선은 Camera를 이동과 함께 회전하는 것처럼 보이는 경우가 있습니다. 이것은 의도적인 것입니다.
  • 라인 오브젝트는 GameObject에서 유일한 렌더러여야 합니다.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

출처: https://seonbicode.tistory.com/22

이 글은 LineRenderer Component 를 사용하여 Unity(C#) 화면에 선을 그리는 방법에 대한 흥미로운 내용을 담고 있습니다.

Unity Documentation 는 here 에서 아주 명확한 방법으로 그것을 설명하기 위하여 작성되어 있습니다.

그러나 실행 시 사용되는 스크립트, 즉 예제를 추가하는 방법에는 어떤 정보가 없습니다.

기본적인 이해를 돕기 위해 이 곳에 예제를 작성해봅니다.

using UnityEngine;
using System.Collections;
 
public class DrawLineTest : MonoBehaviour {
    private LineRenderer line;
    private Vector3 mousePos;
    private Vector3 startPos;
    private Vector3 endPos;
 
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (line == null)
                createLine();
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            line.SetPosition(0, mousePos);
            line.SetPosition(1, mousePos);
            startPos = mousePos;
        }
        else if (Input.GetMouseButtonUp(0) && line)
        {
            if (line)
            {
                mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                mousePos.z = 0;
                line.SetPosition(1, mousePos);
                endPos = mousePos;
                addColliderToLine();
                line = null;
            }
        }
        else if (Input.GetMouseButton(0))
        {
            if (line)
            {
                mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                mousePos.z = 0;
                line.SetPosition(1, mousePos);
            }
        }
    }
    // Following method creates line runtime using Line Renderer component
    private void createLine()
    {
        line = new GameObject("Line").AddComponent();
        line.material = new Material(Shader.Find("Diffuse"));
        line.SetVertexCount(2);
        line.SetWidth(0.1f, 0.1f);
        line.SetColors(Color.black, Color.black);
        line.useWorldSpace = true;
    }
    // Following method adds collider to created line
    private void addColliderToLine()
    {
        BoxCollider col = new GameObject("Collider").AddComponent();
        col.transform.parent = line.transform; //Collider is added as child object of line
        float lineLength = Vector3.Distance(startPos, endPos); //length of line
        // size of collider is set where X is length of line, Y is width of line, Z will be set as per requirement
        col.size = new Vector3(lineLength, 0.1f, 1f);
        Vector3 midPoint = (startPos + endPos) / 2;
        col.transform.position = midPoint; // setting position of collider object
        // Following lines calculate the angle between start Pos and endPos
        float angle = (Mathf.Abs(startPos.y - endPos.y) / Mathf.Abs(startPos.x - endPos.x));
        if ((startPos.y < endPos.y && startPos.x > endPos.x) || (endPos.y < startPos.y && endPos.x > startPos.x))
        {
            angle *= -1;
        }
 
        if (angle != angle) // check NaN        
        {
            Destroy(line.gameObject); // NaN? Destroy gameObject
        }
        else // Not NaN
        {
            angle = Mathf.Rad2Deg * Mathf.Atan(angle);
            col.transform.Rotate(0, 0, angle);
        }    
    }
}

script 를 저장한 후 Unity 로 돌아갑니다.

인제 Scene 을 실행을 하면 화면에 아무것도 없는 것을 보고 실망을 했을 수 있습니다.

하지만 당신은 이미 Line 을 만들 수 있습니다!

화면에서 오른쪽 버튼을 누른 채 드래그를 하면 Line 이 생성되는 것을 볼 수 있습니다.

감사합니다~

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

출처: https://hyunity3d.tistory.com/587

 

FPS 게임에서나 당구 게임에서 레이저 효과를 구현하려고 한다.

유니티 내에 제공하는 LineRenderer 라는 컴포넌트에서 이것을 지원해준다.

먼저 LineRenderer 컴포넌트를 빈 게임 오브젝트에 설치한다.

 

 

컴포넌트에서 Materials 를 설정해 줄수 있고

Positions 로 처음 위치 마지막 위치를 설정해 줄수도 있다.

그리고 선 길이도 설정해줄수 있다.

 

아래 스크립트를 붙이고 메트리얼도 유니티에서 제공되는 기본 파티클 메트리얼을 하나 입혀보자.

 

 

using UnityEngine;

using System.Collections;

 

public class lineRendererTest : MonoBehaviour

{

    private LineRenderer lineRenderer;

 

    // Use this for initialization

    void Start ()

    {

        //라인렌더러 설정

        lineRenderer = GetComponent<LineRenderer>();

        lineRenderer.SetColors(Color.red, Color.yellow);

        lineRenderer.SetWidth(0.1f, 0.1f);

 

        //라인렌더러 처음위치 나중위치

        lineRenderer.SetPosition(0, transform.position);

        lineRenderer.SetPosition(1, transform.position + new Vector3(0,10,0));

         

    }

     

    // Update is called once per frame

    void Update ()

    {

    }

}

 

 

 

아래 그림처럼 처음위치(0,0,0) 에서 위로 쭉 레이저 같은 선이 생기는 것을 볼수 있다.



출처: https://hyunity3d.tistory.com/587 [Unity3D]

 

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

출처: https://funfunhanblog.tistory.com/117

 

유니티) 포물선 궤적그리기

 

포탄을 날리거나 포탄 궤적을 보여주기 위해 사용된다.

유니티에서는 Line Renderer을 이용해봤다.

 

 

나는 포탄궤적이 아닌 캐릭터가 날아갈 점프 궤적을 그리는데 이용했다.

 

스크립트

 

셋팅

 

playerPlane :  라인이 그려질 plane(땅)의 위치를 셋팅해준다. 궤적이 시작하는 위치

 

마우스로 캐릭터 방향바꾸기 글에서 학습한적이 있었다.

https://funfunhanblog.tistory.com/40 (평면을 결정하는 최소 조건)

 

targetPoint는 포물선이의 끝점이된다. (내 게임에서는 노란색 circle에서 최종 위치를 받아온다)

 

체크

 

 

Raycast를 통해 마우스가 위치하는 곳을 가져온다. 

center : 시작벡터와 착지위치벡터의 합에 1/2은 위치가 포물선의 중간위치가 된다.

targetRotation : 라인위치와 최종위치를 빼면 포물선의 방향백터를 구할 수 있다. 

(벡터OA -벡터 OB = 벡터BA) center가 아닌 캐릭터의 위치로 계산해도됨)

Physics.Linecast : 포물을 그리는 라인에 물체가 걸리면 부딪힌 지점을 넘겨준다.

 

 

실제로 궤적(라인)을 그리는 부분

 

 

 

theArc : 두 벡터 사이를 원하는 간격으로 보간 부분

(이해를 못함.. 이쪽은 공부가 필요하다)

lineRenderer.SetPosition : 위에서 구해준 라인의 벡터들의 위치를 설정

 

 

학습참고 : http://maedoop.dothome.co.kr/660

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

출처: https://answers.unity.com/questions/8338/how-to-draw-a-line-using-script.html

How to draw a line using script

void DrawLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f) 
         { 
             GameObject myLine = new GameObject(); 
             myLine.transform.position = start; 
             myLine.AddComponent(); 
             LineRenderer lr = myLine.GetComponent(); 
             lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply")); 
             lr.SetColors(color, color); 
             lr.SetWidth(0.1f, 0.1f); 
             lr.SetPosition(0, start); 
             lr.SetPosition(1, end); 
             GameObject.Destroy(myLine, duration); 
         }

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

출처: https://answers.unity.com/questions/1571674/multiple-lines-in-3d-using-linerenderer-in-one-scr.html

 

Multiple Lines in 3D using LineRenderer in one Script

Hi there,

so I want to draw lines between different GameObjects in 3D.!

I have two fbx-models with body parts. Those models are moving. The lines to be drawn should be between eg: LeftForeArm of the one Model, and the LeftForeArm of the other model. There needs to be lines between all the body components between model 1 and model 2.

What I know so far: I can only use one static LineRenderer in one script. I need to dynamically create a List with LineRenderers for all body parts - but I cant figure it out myself!

This is the initialization code snippet:

 

   private void drawingLinesInitialization()
     {
         // Line Renderer Initialization
         LineRenderer lineRendererLeftForeArm  = gameObject.AddComponent();
 
         //Line Renderer Colors / Materials
         lineRendererLeftForeArm.material  = new Material(Shader.Find("Sprites/Default"));
 
         //Line Renderer Width
         lineRendererLeftForeArm.widthMultiplier = 0.05f;
 
         /*
          * A simple 2 color gradient with a fixed alpha of 1.0f.
          * ColorGradient retrieved from Unity example:
          * https://docs.unity3d.com/ScriptReference/LineRenderer.SetPosition.html at the 14.11.2018
          * 
          */
         float alpha = 1.0f;
         Gradient gradient = new Gradient();
         gradient.SetKeys(
             new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) },
             new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
             );
         lineRendererLeftForeArm.colorGradient = gradient;
 
     }

 

 

This is the code I have so far for one comparison:

 

 IEnumerator coroutineDrawingSystem()
     {
         while (true)
         {
             //Debug.Log("Coroutine Drawing System called");
             //Getting Components:
             LineRenderer lineRendererLeftForeArm = GetComponent();
 
             //Checking if GameObjects are initialized and then drawing
             if (cLeftForeArm != null && lLeftForeArm != null)
             {
                 // Update position of the two vertex of the Line Renderer
                 lineRendererLeftForeArm.SetPosition(0, cLeftForeArm.transform.position);
                 lineRendererLeftForeArm.SetPosition(1, lLeftForeArm.transform.position);
 
             } else
             {
                 Debug.Log("Some Transforms of objects are not initialized!");
             }


              yield return new WaitForSeconds(timeBetweenLineRenderDrawing);
         }
     }

 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 

 

*기타관련링크

https://ssscool.tistory.com/347

 

 

 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



출처: https://202psj.tistory.com/1286?category=640054 [알레폰드의 IT 이모저모]

728x90
반응형