Unity LineRenderer 之 从屏幕中心画Line

2025-10-23 07:09:33

1、ScreenToWorldPoint:

1)功能简述

public Vector3 ScreenToWorldPoint(Vector3 position);

Transforms position from screen space into world space.

Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.

2、LineRenderer.SetPositions:

1)功能简述

public void SetPositions(Vector3[] positions);

positions:The array of positions to set.

Set the positions of all vertices in the line.

This method is preferred to SetPosition when setting all positions, as it is more efficient to set all positions using a single command than to set each position individually.

1、打开Unity,新建一个工程,具体如下图

Unity LineRenderer 之 从屏幕中心画Line

2、在场景中,新建一个“Plane”,具体如下图

Unity LineRenderer 之 从屏幕中心画Line

3、在场景中,新建一个“GameObject”,然后给“GameObject”添加“LineRenderer”组件,“LineRenderer”参数如下图,再新建一个“Material”,赋给“LineRenderer”,具体如下图

Unity LineRenderer 之 从屏幕中心画Line

4、在工程中,新建一个脚本“LineRendererTest”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图

Unity LineRenderer 之 从屏幕中心画Line

5、在“LineRendererTest”脚本上编写代码,首先获取“LineRenderer”组件,然后获取屏幕中心点转为世界坐标,接着通过射线设置“LineRenderer”的第二个点,结合第一个点画出“LineRenderer”,具体代码和代码说明如下图

Unity LineRenderer 之 从屏幕中心画Line

6、“LineRendererTest”脚本的具体内容如下:

using UnityEngine;

public class LineRendererTest : MonoBehaviour {

    public LineRenderer line;

    private Vector3 screenCenterPoint;

    // Use this for initialization

    void Start () {

        screenCenterPoint = Camera.main.ScreenToWorldPoint 

            (new Vector3(Screen.width / 2, Screen.height / 2, 1));

    }

        // Update is called once per frame

    void Update () {

        if (Input.GetMouseButtonDown (0)) {

            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

            RaycastHit hitInfo;

            if(Physics.Raycast (ray, out hitInfo)){

                line.SetPositions (new Vector3[]{screenCenterPoint, hitInfo.point});

            }

        }

    }

}

7、脚本编译正确,回到Unity界面,把脚本赋给“MainCamera”,并“GameObject”的“LineRenderer”赋值给脚本,具体如下图

Unity LineRenderer 之 从屏幕中心画Line

8、运行场景,任意点击游戏视图中的“Plane”,都会从屏幕中心到“Plane”平面点画出“LineRenderer”线,具体如下图

Unity LineRenderer 之 从屏幕中心画Line

9、到此,《Unity LineRenderer 之 从屏幕中心画Line》讲解结束,谢谢

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢