射线的应用

来源:互联网 发布:科研立项题目 软件 编辑:程序博客网 时间:2024/05/14 03:28

  欢迎来到unity学习、unity培训、unity企业培训教育专区,这里有很多U3D资源、U3D培训视频、U3D教程、U3D常见问题、U3D项目源码,我们致力于打造业内unity3d培训、学习第一品牌。  

  射线,类比的理解就是游戏中的子弹。是在3D世界里中一个点向一个方向发射的一条无终点的线。在发射的过程中,一旦与其他对象发生碰撞,就停止发射。

     射线包括两个元素:ray.origin(射线起点);ray.direction(射线的方向)

     创建一个射线的方法:ray(origin : vector3,direction : vector3) 

           定义一个光线投射碰撞:raycasthit hit;

           发射射线长度为:physics.raycast(ray,out hit,100);

           打印射线:debug.drawline(ray.origin,jit.point)

using UnityEngine;

using System.Collections;

 

public class RayTest : MonoBehaviour {

 

    // Use this for initialization

    void Start () {

    

    }

    

    // Update is called once per frame

    void Update () 

    {

        if(Input.GetMouseButton(0))

        {

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//从摄像机发出到点击坐标的射线

            RaycastHit hitInfo;

            if(Physics.Raycast(ray,out hitInfo))

            {

                Debug.DrawLine(ray.origin,hitInfo.point);//划出射线,只有在scene视图中才能看到

                GameObject gameObj = hitInfo.collider.gameObject;

                Debug.Log("click object name is " + gameObj.name);

                if(gameObj.tag == "boot")//当射线碰撞目标为boot类型的物品 ,执行拾取操作

                {

                    Debug.Log("pick up!");

                }

            }

        }

    }

}

自动寻路

private NavMeshAgent agent;

void Start() {

      agent = GetComponent<NavMeshAgent>();

}

void Update() {

RaycastHit hit;

if (Input.GetMouseButtonDown(0)) {

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit)){

agent.SetDestination(hit.point);

}

}

 

 

 

0 0
原创粉丝点击