Unity的LineRender组件在带有碰撞体的物体上画线
原理很简单:就是根据场景中的2个点(StartPoint、EndPoint),在这2个点中取设定的多个点(Vector3.Lerp),通过记录这些点往需要的位置(Vector3.down)反射射线,射线碰撞到Collider返回位置信息,从而实现类似绳子落在物体上的效果。
1、新建一个脚本,命名为RayLine。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayLine : MonoBehaviour
{
//Line起点
public Transform startpoint;
//Line终点
public Transform endpoint;
public Vector3 rayPosition;
//Line的点数,越大越精细
public Vector3[] points = new Vector3[20];
public LineRenderer line;
//调整LinePoint的物体
float y = 0.001f;
private void Start()
{
line.positionCount = points.Length;
}
Vector3 tempVec3;
int index;
void Update()
{
//射线发射,碰撞到Collider,记录碰撞点,后期赋值给LinePoint
for (int i = 0; i < points.Length; i++)
{
rayPosition = Vector3.Lerp(startpoint.position, endpoint.position, (float)i / points.Length);
RaycastHit hit;
if (Physics.Raycast(rayPosition+new Vector3(0,0.1f,0), Vector3.down, out hit))
points[i] = hit.point + new Vector3(0, y, 0);
}
//LineRender在Collider边缘的调整,可去掉
for (int i = 1; i < points.Length; i++)
{
if (points[i].y > points[i - 1].y)
{
index = i;
tempVec3 = points[i];
float y = points[i].y;
points[i] = new Vector3(points[i - 1].x, y, points[i - 1].z);
break;
}
}
for (int i = index + 1; i < points.Length - 1; i++)
{
if (i == index + 1)
points[i] = tempVec3;
else
{
if (points[i].y > points[i + 1].y)
{
tempVec3 = points[i + 1];
float y1 = points[i].y;
points[i] = new Vector3(tempVec3.x, y1, tempVec3.z);
break;
}
}
}
//返回Line点
for (int i = 0; i < points.Length; i++)
{
//设置点
line.SetPosition(i, points[i]);
}
}
}
2、在场景中创建一些物体,摆放在需要位置(根据需要随意摆放,就不演示了)。
3、将RayLine脚本拖入到摄像机上,并根据图示设置好参数。
4、在场景中新建LineRender,数值设置如下(根据自己的需求设置)。
5、最终演示效果。
——有不足或功能强化的地方,欢迎各位猿友私信或评论