简体   繁体   English

当敌人看到玩家时让他攻击

[英]Let a enemy attack when he sees the player

Can someone help me I am using the code below to try to let the enemy look if he can see the player or not.有人可以帮助我吗我正在使用下面的代码来尝试让敌人看看他是否可以看到玩家。

But the problem is can he still see me when I am behind a wall Can someone help me out ?但问题是当我躲在墙后他还能看到我有人可以帮我吗?

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");
        }
    }
}

Like @BugFinder mentioned, you are only checking that the RayCast did collide with something and not necessarily the player.就像@BugFinder 提到的那样,您只是在检查RayCast确实与某些东西发生了碰撞,而不一定是玩家。

If you want to determine if the ray is colliding with only the player, and not another object, use the function overload that sets a RaycastHit object.如果您想确定光线是否仅与玩家碰撞,而不与其他对象碰撞,请使用设置RaycastHit对象的函数重载。 Then you can get the tag and compare it with the tag of your player.然后您可以获取tag并将其与您的播放器的标签进行比较。 (see Physics.RayCast and RaycastHit ) (参见Physics.RayCastRaycastHit

You could achieve this like so:你可以这样实现:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM