ray射线折射绘制路径

转载自注明: http://www.ceeger.com/forum/read.php?tid=10760&fid=2&page=1#123692 

任何用过Ray这个类的人都知道,射线不提供折射功能,而折射在某些场合是非常重要的。所以这篇教程将尝试提供一个方案,来解释如何使一束射线碰到一个表面时折射。除此之外,还可以设置射线折射的次数。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ray1 : MonoBehaviour {


//一条射线

private Ray ray;

//本物体的Transform

private Transform trans;


//line renderer组件上点的数量

private int pointNum;

//添加的line renderer组件

private LineRenderer lineRender;

//折射次数

public int reflectionNum = 10;

//一个RaycastHit类型的变量, 可以得到射线碰撞点的信息

private RaycastHit hit;


//折射的方向

private Vector3 dir;

// Use this for initialization
void Start () {
    //初始化组件

    trans = this.GetComponent<Transform>();

    lineRender = this.GetComponent<LineRenderer>();
}
bool istrue = false;
// Update is called once per frame
void Update () {
     
    ray = new Ray(trans.position, trans.forward);
    Debug.DrawRay(trans.position, trans.forward*100, Color.green);

    dir = trans.forward;


    pointNum = 1;
    lineRender.SetVertexCount(pointNum);
    lineRender.SetPosition(0, trans.position);

    for (int i = 0; i < reflectionNum; ++i)
    {
        istrue = Physics.Raycast(ray.origin, ray.direction, out hit);
        if (istrue)
        {
            
            Debug.Log(hit.normal);
            //Debug.DrawRay(hit.point, hit.normal, Color.red);

            dir = Vector3.Reflect(ray.direction, hit.normal);
            ray = new Ray(hit.point, dir);

            Debug.DrawRay(hit.point, hit.normal * 5, Color.blue);
            Debug.DrawRay(hit.point, dir * 100, Color.green);

            //          Debug.Log("Object name: " + hit.transform.name);

            lineRender.SetVertexCount(++pointNum);
            lineRender.SetPosition(i + 1, hit.point);
        }
        else
        {
            lineRender.SetVertexCount(++pointNum);
            lineRender.SetPosition(i + 1, hit.point+dir * 100);
        }

    }
    
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值