转载自注明: 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);
}
}
}
}