Unity3D中射线的相关使用

①利用射线和自动寻路实现在小地图中点击场景中物体实现目标移动
代码:

public class MapCameraRayTest : MonoBehaviour
{
    [SerializeField]
    private Camera mapCamera;
    private RaycastHit hit;
    private NavMeshAgent agent;
    private void Start ()
    {
        agent = GetComponent<NavMeshAgent> ();
    }

    private void Update ()
    {
        Ray ray = mapCamera.ScreenPointToRay (Input.mousePosition);
        if(Physics.Raycast(ray,out hit,100) && Tag.Hourse == hit.transform.tag && Input.GetMouseButton(0))
        {
            Debug.DrawLine (mapCamera.transform.position,hit.point,Color.red);
            agent.SetDestination (hit.transform.position);
        }
    }
}

②利用射线实现拾取物体:

public class Pickup : MonoBehaviour 
{
    [SerializeField]
    private Transform handlerTF;
    private RaycastHit hit;
    private Transform carryTF;
    private bool isPickup;
    [SerializeField]
    private Transform uiPoint;

    private void Update () {
        if (Physics.Raycast (handlerTF.position, handlerTF.forward, out hit, 2) &&
            Tag.Hourse == hit.transform.tag)
        {
            uiPoint.gameObject.SetActive (true);
            uiPoint.position = Camera.main.WorldToScreenPoint (hit.point);
            if (!isPickup) 
                carryTF = hit.transform;
        } 
        else
            uiPoint.gameObject.SetActive (false);
        if (null == carryTF) return;
        if (Input.GetMouseButton(0)) {
            carryTF.parent = handlerTF;
            carryTF.localPosition = new Vector3(0,0,1);
            carryTF.localEulerAngles = Vector3.zero;
            isPickup = true;
        } 
        else
        {
            isPickup = false;
            carryTF.parent = null;
            carryTF.localEulerAngles = new Vector3 (0, carryTF.localEulerAngles.y, 0);
            carryTF = null;
        }
    }
}

③发射激光线:

public class Shoot : MonoBehaviour
{
    [SerializeField]
    private Transform uiPoint; 
    private RaycastHit hit; 
    private LineRenderer linearRenderer;
    private void Start () 
    {
        linearRenderer = GetComponent<LineRenderer> ();
    }

    private void Update () {
        if (Physics.Raycast (this.transform.position, this.transform.forward, out hit, 100)
            && Input.GetMouseButton(0) ) 
        {
            uiPoint.gameObject.SetActive (true);
            uiPoint.position = Camera.main.WorldToScreenPoint(hit.point);
            linearRenderer.enabled = true;
            linearRenderer.SetPosition(0,this.transform.position);
            linearRenderer.SetPosition (1,this.hit.point);
        } 
        else
        {
            uiPoint.gameObject.SetActive (false);
            linearRenderer.enabled = false;

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值