在OnBecameVisible中遇到问题(能够穿墙并在场景视图中可见)

huangapple go评论66阅读模式
英文:

Having problems with OnBecameVisible (sees through walls and is visible on scene view)

问题

我正在尝试创建一个脚本,使敌人只在玩家摄像机可见并且玩家按下空格键时才追逐玩家。我一直在尝试使用render.isVisible,但遇到了两个主要问题:

  1. 即使敌人在场景视图中可见,isVisible也被启用,使测试变得不可能。

  2. isVisible可以穿墙而过,所以如果玩家望向一堵墙,而敌人在墙后面,它仍然会注册为isVisible

请帮帮我,我都要疯了。谢谢!

public NavMeshAgent enemy;
public Transform player;

Renderer m_Renderer;

private void Start()
{
    m_Renderer = GetComponent<Renderer>();
}

private void OnBecomeInvisible()
{
    enabled = false;
}

void OnBecameVisible()
{
    enabled = true;

    if (Input.GetKey(KeyCode.Space) && m_Renderer.isVisible)
    {
        Debug.Log("is visible");

        enemy.SetDestination(player.position);
    }
}

private void Update()
{
    OnBecameVisible();
}

老实说,我不太确定要尝试什么,非常感谢您的任何帮助!

英文:

I'm trying to make a script that has an enemy chase the player only if the enemy is viewable by the player camera and the player hits the space key. I've been trying to use render.isVisible but run in to two MAJOR problems:

  1. isVisible is enabled even if the enemy is visible in the scene view, making testing impossible.

  2. isVisible works through walls, so if the player is looking at a wall and the enemy is behind it, it still registers as isVisible.

Please help I'm losing my mind. Thank you!

public NavMeshAgent enemy;
public Transform player;

Renderer m_Renderer;

private void Start()
{
    m_Renderer = GetComponent&lt;Renderer&gt;();
}

private void OnBecomeInvisible()
{
    enabled = false;
}

void OnBecameVisible()
{
    enabled = true;

    if (Input.GetKey(KeyCode.Space) &amp;&amp; m_Renderer.isVisible)
    {
        Debug.Log(&quot;is visible&quot;);

        enemy.SetDestination(player.position);
    }

}

private void Update()
{
        OnBecameVisible();
}

I'm honestly not sure what to try, thank you so much for any help!

答案1

得分: 2

IsVisible 实际上不是为此使用而设计的。它只表示对象是否被任何相机渲染。请查看此处的文档:https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html

要确定一个实体是否被另一个实体实际可见,通常需要进行视锥体检查,然后进行一个或多个射线投射来确定目标是否被遮挡。

英文:

IsVisible is really not designed for that usage. It just means object is being rendered by any camera. See the documentation here: https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html

To determine whether something is actually visible from one entity by another, you typically have to do a frustum check followed by one or more raycasts to determine whether the target is blocked.

huangapple
  • 本文由 发表于 2023年2月19日 04:55:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定