Unity LineRenderer 之 从屏幕中心画Line

 时间:2026-02-14 12:27:58

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》讲解结束,谢谢

  • 如何用C4D的TFD做出水墨爆开的效果
  • After Effects CC 2020 下载安装教程
  • photoshop运用技巧:[3]如何制作阳光投影效果
  • unity 3d 2019软件中如何修改文本样式
  • maya破碎插件pdi怎么使用?
  • 热门搜索
    手抄报主题 手抄报的图片 小学消防手抄报大全 海洋知识手抄报 我运动我健康手抄报 地理手抄报图片 快乐数学手抄报 诚信手抄报版面设计图 让世界充满爱手抄报 依法治校手抄报