英文:
Having problems with OnBecameVisible (sees through walls and is visible on scene view)
问题
我正在尝试创建一个脚本,使敌人只在玩家摄像机可见并且玩家按下空格键时才追逐玩家。我一直在尝试使用render.isVisible
,但遇到了两个主要问题:
-
即使敌人在场景视图中可见,
isVisible
也被启用,使测试变得不可能。 -
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:
-
isVisible is enabled even if the enemy is visible in the scene view, making testing impossible.
-
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<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 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论