返回首页DA系统C#IDE文件同步服务屏保 今天是: 2026-05-05    "立夏"  夏季的第一个节气,表示盛夏时节的正式开始

搜索
热搜: linux 技术
Hi~登录注册
查看: 1972|回复: 0

[原创] 【原创】射线检测讲解

[复制链接]
发表于 2022-2-28 19:23:51 | 显示全部楼层 |阅读模式

少侠不来段修仙之旅吗~

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
//射线检测讲解

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ZDScript : MonoBehaviour
{
    //注意:如果movespeed物体移动速度过快(一般大于200以上),碰撞检测方法(OnTriggerEnter、OnCollisionEnter)将失效
    //解决方案:游戏开始时,使用射线检测

    public float movespeed = 300;

    //射线检测的目标物体信息
    RaycastHit hit;

    public LayerMask make; //层级物体类型,要public类型,方便在unity面板选择
    bool rayPdl;

    //最远距离
    private int MaxDistance = 100;

    //目标位置
    Vector3 tagD;

    private void Start()
    {
        //物理类的Raycast方法讲解
        //Raycast 方法的重载15 讲解
        //Physics.Raycast(起点坐标,方向(正前方:this.transform.forward),返回的射线受击物体信息,射线发射最大距离,检测哪个层级物体?)  
        //如敌人在NPC层,其他层的物体射线就不再检测,只检测NPC层中的物体!!--重点
        //Physics.Raycast 返回bool值,意味射线检测到了吗
        rayPdl = Physics.Raycast(this.transform.position, this.transform.forward, out hit, MaxDistance, make);
        if (rayPdl == true)
        {//射线检测到物体
            //检测到物体时,子弹目标位置前进至目标物体点即可
            tagD = hit.point; //击中的位置
            print(hit.point);
        }
        else
        {//射线没有检测到物体
            //如果没有检测到物体时,子弹就向前前进至子弹前方100米
            tagD = this.transform.position + this.transform.forward * MaxDistance;
            print("没有检测到目标");
        }
    }

    private void Update()
    {
        //Time.frameCount 属性是查看当前过了多少帧帧
        print(Time.frameCount + "--" + this.transform.position);

        //子弹每帧匀速移动(Vector3.MoveTowards)
        this.transform.position = Vector3.MoveTowards(this.transform.position, tagD, Time.deltaTime * movespeed);
        if ((this.transform.position- tagD).sqrMagnitude < 0.1f)
        {
            print("接触目标点");
            Object.Destroy(this.gameObject);//接触之后销毁子弹
        }
    }
}



游客
回复
*滑块验证:

DA论坛飞机票来了~
快速回复 返回顶部 返回列表