射线的应用

  欢迎来到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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值