手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

Unity LineRenderer 之 从屏幕中心画Line

时间:2024-10-12 23:11:57

Unity LineRenderer 之 从屏幕中心画Line。本节介绍,获取屏幕中心,转为世界坐标,然后通过射线获取LineRenderer的第二个点,从屏幕中心,向外画出一条“LineRenderer”的简单案例,具体如下

工具/原料

Unity

LineRenderer

一、知识要点

1、ScreenToWorldPoint:1)功能简述publicVector3ScreenToWorldPoint(Vector3pos足毂忍珩ition);Transformspositionfrom 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 voidSetPositions(Vector3[]positions);positions:The arra烤恤鹇灭y of positions to set.Set the positions of all vertices in the line.This method is preferred toSetPositionwhen setting all positions, as it is more efficient to set all positions using a single command than to set each position individually.

二、LineRenderer 之 从屏幕中心画Line

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、“LineRenderer哌囿亡噱Test”脚本的具体内容如下:usingUnityEngine;publicclassLineRendererTest:MonoBehaviour{publicLineRendererline;privateVector3screenCenterPoint;//Usethisforinitialization voidStart(){screenCenterPoint=Camera.main.ScreenToWorldPoint (newVector3(Screen.width/2,Screen.height/2,1)); } //Updateiscalledonceperframe voidUpdate(){if(Input.GetMouseButtonDown(0)){Rayray=Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHithitInfo; if(Physics.Raycast(ray,outhitInfo)){line.SetPositions(newVector3[]{screenCenterPoint,hitInfo.point}); } } }}

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

Unity LineRenderer 之 从屏幕中心画Line

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

Unity LineRenderer 之 从屏幕中心画Line

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

© 手抄报圈