LoginSignup
5

More than 5 years have passed since last update.

Unityのline rendererで絵を描く

Posted at

1.set up a default renderer


        defaultRenderer = gameObject.GetComponent();
        defaultRenderer.material = new Material (shader);
        defaultRenderer.SetVertexCount (0);
        defaultRenderer.SetWidth (0.1f, 0.1f);
        defaultRenderer.SetColors (Color.green, Color.green);
        defaultRenderer.useWorldSpace = true;

2.create a panel to draw on


        panel = GameObject.Find ("DrawingPanel");

3.the main code in Update()


        if (Input.GetMouseButtonDown (0)) {
            //to check if this line renderer is used. If it is, create a new line renderer(on a new Gameobject)
            //(so that more than 1 lines can be rendered)
            if(!used){
                used = true;
                isMousePressed = true;
                defaultRenderer.SetVertexCount (0);
                pointList.RemoveRange (0, pointList.Count);
            }else if(!newCreated){
                //to draw more than 1 lines, we have to create a new gameObejct
                GameObject newRenderer = GameObject.Instantiate (rendererPrefab);
                newCreated = true;
                newRenderer.GetComponent ().init(id+1);
            }
        }
        if (Input.GetMouseButtonUp (0)) {
            isMousePressed = false;}
        if (isMousePressed) {
            mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            mousePos.z = 0;
            if (Input.mousePosition.x < panel.GetComponent().offsetMin.x || 
                Input.mousePosition.x > (Screen.width + panel.GetComponent().offsetMax.x)){ 
                return;
            }
            //To draw just in the area of panel
            if (Screen.height - Input.mousePosition.y < (-panel.GetComponent().offsetMax.y) || 
                Screen.height - Input.mousePosition.y > (Screen.height - panel.GetComponent().offsetMin.y)){ 
                return;
            }
            if (!pointList.Contains (mousePos)) {
                pointList.Add (mousePos);
                defaultRenderer.SetVertexCount (pointList.Count);
                defaultRenderer.SetPosition (pointList.Count - 1, (Vector3)pointList [pointList.Count - 1]);
            }
        }

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5