【Unity的LineRender组件在带有碰撞体的物体上画线】

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,数值设置如下(根据自己的需求设置)。
LineRender设置

5、最终演示效果。
最终效果

——有不足或功能强化的地方,欢迎各位猿友私信或评论

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

᭄ꦿდ玖日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值