栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity Vector3.Reflect反射线使用和计算原理(光打到平面上反射)

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity Vector3.Reflect反射线使用和计算原理(光打到平面上反射)

计算向量投射到物体上的反射向量 

碰撞模拟:
public class test3 : MonoBehaviour
{
    Vector3 dir;
    Vector3 pos;
    private void Start()
    {
        dir = transform.right;
        pos = transform.position;
    }

    private void Update()
    {
        transform.position += dir * Time.deltaTime*4;
    }
    
    private void OnCollisionEnter2D(Collision2D collision)
    {        
        Vector2 inDirection = (transform.position - pos).normalized;
        Vector2 inNormal = collision.contacts[0].normal;
        dir = Vector2.Reflect(inDirection, inNormal);
        pos = transform.position;
    }
}
射线模拟:

红线:inDirection
绿线:inNormal 法线
蓝线:Result 反射线

 

public Transform tsTarget;//目标点
void OnDrawGizmos()
{
#if UNITY_EDITOR
    Color prevColor = Gizmos.color;

    //红线的方向
    Vector3 dir = tsTarget.position - transform.position;

    //从原点向终点打出一条红色的射线
    Gizmos.color = Color.red;
    RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, dir, Mathf.Infinity);
    Gizmos.DrawLine(transform.position, hitInfo.point);//画红线

    //射线碰到碰撞物的法线
    Gizmos.color = Color.green;
    var normal = hitInfo.point + hitInfo.normal;//法线0,0点为基准,所以这里要加上碰撞点的位置
    Gizmos.DrawLine(hitInfo.point, normal);//画绿线

    Gizmos.color = Color.blue;
    Vector2 direction = (Vector2)hitInfo.point + Vector2.Reflect((Vector2)dir, (normal - hitInfo.point));//Vector2.Reflect求反射,但是会出现偏移,经过我反复验证得出的结果
    Gizmos.DrawLine(hitInfo.point, direction);//画蓝线

    Gizmos.color = prevColor;

#endif
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/900472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号