首页 > 解决方案 > 当敌人看到玩家时让他攻击

问题描述

有人可以帮我吗?我正在使用下面的代码来尝试让敌人看他是否能看到玩家。

但问题是当我在墙后他还能看到我有人能帮帮我吗?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;

public class Test : MonoBehaviour
{
    [SerializeField]
    float distance;

    public GameObject player;
    public Transform Shootpoint;

    public bool CanSee = false;

    [SerializeField]
    float chaseDistence = 0.5f;



    void Update()
    {
        distance = Vector3.Distance(Shootpoint.position, player.transform.position);

        if (!Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
        {
            Debug.DrawLine(Shootpoint.position, player.transform.position, Color.red);
            CanSee = false;
            Debug.Log("CANT SEE");

        }
        else if (Physics.Raycast(Shootpoint.position, player.transform.position, chaseDistence))
        {
            Debug.DrawLine(Shootpoint.position, player.transform.position, Color.green);
            CanSee = true;
            Debug.Log("CAN SEE");
        }
    }
}

标签: c#unity3d

解决方案


就像@BugFinder 提到的那样,您只是在检查是否确实与某些东西RayCast发生了碰撞,而不一定是与玩家发生了碰撞。

如果您想确定光线是否仅与玩家碰撞,而不与其他对象发生碰撞,请使用设置RaycastHit对象的函数重载。然后你可以得到tag它并将它与你的播放器的标签进行比较。(参见Physics.RayCastRaycastHit

你可以这样实现:

RaycastHit hitInfo;
if(Physics.Raycast(Shootpoint.position, player.transform.position, out hitInfo, chaseDistence)) 
{
    if (hitInfo.collider.CompareTag("player"))
    {
        // Can see
    }
    else 
    {
        // Can't see, raycast hit something
    }
}
else
{
    // Can't see, raycast hit nothing
}

推荐阅读