【问题标题】:Unity use layer mask to temporarily ignore raycastunity 使用图层蒙版暂时忽略光线投射
【发布时间】:2016-08-11 14:53:24
【问题描述】:

我已经阅读了有关此问题的其他问题,但没有一个可以解决我的问题。我正在制作一个游戏,如果 AI 靠近玩家,它会向后移动[如果光线击中一定距离,光线投射会切换一个布尔值],但是因为这是在更新函数中,所以光线每帧都会更新并且然后在我不想要它时切换布尔值,因为我已经启动了代码以使 AI 向后移动,请有人告诉我如何使用图层蒙版在“避免”布尔值时暂时停止光线投射true ,所以当 AI 向后移动时,光线投射会被忽略,代码;

void Update () 
    {
        //raycasting
        RaycastHit hit;
        Ray ray = new Ray(transform.position, Vector3.forward);

        //check if raycast hit player
        if (Physics.Raycast(ray, out hit, 2))
        {
            if (hit.collider.tag == "PlayerFront")
            {
                avoid = true;
                movementSpeed = 0;
            }
        }
        else
        {
            movementSpeed = 2f;
            avoid = false;
        }

        if (avoid == true)
        {
            startPos = enemy.transform.position;
            endPos = enemy.transform.position + Vector3.back * distance;

            currentLerpTime += Time.deltaTime;
            if (currentLerpTime >= lerpTime)
            {
                currentLerpTime = lerpTime;
            }

            float perc = currentLerpTime/lerpTime;
            enemy.transform.position = Vector3.Lerp(startPos, endPos, perc);

            avoidCount+=1;

            avoid = false;
        }

        else if (avoid == false)
        {
            transform.LookAt(target);
            transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
            currentLerpTime = 0;
        }
    }

【问题讨论】:

  • 为什么你认为应该使用图层蒙版? avoid == true 时根本不进行光线投射不是更容易吗?
  • 您可以选择完成此操作:状态机、使用“IF(false == Avoid)”语句封装调用等... RayCast 是一项非常昂贵的操作。

标签: c# unity3d updates layer raycasting


【解决方案1】:

我的建议是将if (Physics.Raycast... 块放在代码底部的else 块内。 (注意else if (avoid == false) 是多余的,因为avoid 没有其他值可能如果不是true

这意味着您仅在尚未避免时才进行光线投射,这将完成您的要求并提高性能。

但是,还值得注意的是,您的代码当前在 if 块中设置了 avoid = false - 因此您目前一次只能避免一帧。您或许可以考虑找到一种方法,让avoid 保留为true 更长的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多