0

代码:

        void IdleState ()
    {
    RaycastHit hit;

    for (float i = -ViewWidth; i < ViewWidth; i++)
        { 
            float Iterater = i/20;
            if (Physics.Raycast(transform.position, transform.forward + new Vector3(Iterater,0,0), out hit, ViewRange))
             {
                Debug.DrawRay(transform.position,(transform.forward + new Vector3(Iterater,0,0)).normalized * ViewRange, Color.red);
                if (hit.transform.gameObject.layer == LayerMask.NameToLayer("Player"))
                 {
                    FoundPlayer(hit.transform);
                 }
             }
        }

}

问题:在 Unity 中,我试图通过使用 for 循环绘制多个光线投射来为敌方 AI 创建一个视野。出于某种原因,光线投射会这样做: GIF

这几天我一直在尝试解决这个问题,请帮忙!

如果需要,还可以使用 FoundPlayer() 函数:

void FoundPlayer  (Transform DetectedObject)
    { 
        float step = TurnSpeed * Time.deltaTime;
        Vector3 Direc = DetectedObject.position - transform.position;
        Vector3 RotMath = Vector3.RotateTowards(transform.forward, Direc,step,0.0f);
        transform.rotation = Quaternion.LookRotation(RotMath);
        Vector3 CurrentRot = transform.eulerAngles;
        transform.rotation = Quaternion.Euler(0,CurrentRot.y,0);
    }

FoundPlayer() 函数只是在其中一个射线投射击中敌人时将其旋转到玩家身边。

4

1 回答 1

2

关于光线投射:

transform.Forward位于世界空间坐标中,您可以在其中添加世界空间 X 轴偏移的一部分。您想要的是添加“局部空间”X 轴的一部分。 transform.Right是局部空间X轴的世界空间转换。尝试:

var rayDirection = (transform.Forward + (Vector3.Scale(transform.Right, new Vector3(Iterater, 0, 0))).normalized;

关于视野:

如果您只想检查 FOV 中的对象,请开始查找球体中的所有对象,然后将这些对象过滤到适当角度内的对象transform.forward

float ViewRange = 10;
float hHalfFov = 45; // Horizontal Half-Field of View (Degrees)
float vHalfFov = 45; // Vertical Half-Field of View (Degrees)

void IdleState() {

    // Find all colliders within ViewRange
    var hits = Physics.OverlapSphere(transform.position, ViewRange);

    foreach (var hit in hits) {
        if ( hit.gameObject == this.gameObject ) continue; // don't hit self

        // Check FOV
        var direction = (transform.position - hit.transform.position);
        var hDirn = Vector3.ProjectOnPlane(direction, transform.up).normalized; // Project onto transform-relative XY plane to check hFov
        var vDirn = Vector3.ProjectOnPlane(direction, transform.right).normalized; // Project onto transform-relative YZ plane to check vFov

        var hOffset = Vector3.Dot(hDirn, transform.forward) * Mathf.Rad2Deg; // Calculate horizontal angular offset in Degrees
        var vOffset = Vector3.Dot(vDirn, transform.forward) * Mathf.Rad2Deg; // Calculate vertical angular offset in Degrees

        if (hOffset > hHalfFov || vOffset > vHalfFov) continue; // Outside of FOV

        Debug.DrawLine(transform.position, hit.transform.position, Color.red);

        if (hit.transform.gameObject.layer == LayerMask.NameToLayer("Player")) {
            FoundPlayer(hit.transform);
        }
    }
}
于 2019-01-09T03:32:03.067 回答