Raycast击中角色的碰撞器不一致,但始终如一地击中其他一切

时间:2018-06-11 09:28:07

标签: c# unity3d character raycasting collider

我正在制作FPS游戏,我正在尝试编写一种方法来检测敌人何时可以看到我。 我使用光线投射来做到这一点。

我遇到一个问题,即光线投射并不总是击中(巨大的)盒式对撞机,我希望它始终能够击中。

光线投射发生在我的AIShooting剧本中,我希望它能击中我角色的盒子对撞机。

AIShooting脚本如下所示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIShooting : MonoBehaviour {

private GameObject _playerCharacter;        //reference to the player controlled character
private CharacterController _playerCharacterController;
private Collider _characterCollider;
private GameObject _characterWeapon;        //reference to the weapon held by the AI
private int _offSetY = 1;                   //offset from player controlled character pivot point, so it shoots the character in the center
                                            //private LineRenderer _lineRenderer;   

// Use this for initialization
void Start () {

    _playerCharacter = GameObject.Find("Character");
    _playerCharacterController = _playerCharacter.GetComponent<CharacterController>();
    _characterWeapon = _playerCharacter.GetComponent<Character>().EquipedWeapons[0];
    _characterCollider = _playerCharacter.GetComponent<BoxCollider>();

}

// Update is called once per frame
void Update () {
    this.transform.LookAt(_playerCharacter.transform);
    LookForEnemyByShootingRayCast();
}

void LookForEnemyByShootingRayCast()
{
    Vector3 _shootTarget = new Vector3(_playerCharacter.transform.position.x, _playerCharacter.transform.position.y + _offSetY, _playerCharacter.transform.position.z);
    RaycastHit hit;
    if (Physics.Raycast(this.transform.position, _shootTarget, out hit, 10000))     //if the ray cast collides with object
    {
        Debug.DrawLine(this.transform.position, _shootTarget, Color.red);           //make the ray cast visible in scene view
        if (hit.transform.name == _characterCollider.transform.name )   //if the raycast hits the character collider
        {
            Debug.Log("THE ENEMY SEES YOU");
        }
        Debug.Log(hit.transform.name);
    }
}
}

我使用Debug.Drawline()显示光线投射,看起来像这样。 光线从右边的角色射向左边的角色(带有巨大的盒子对撞机)。

然而,只有当我真的非常接近敌人角色时才会触发Debug.Log("THE ENEMY SEES YOU");行,即使这样,它也会在某些位置发生并且根本不一致。

Raycast display

提前致谢!

2 个答案:

答案 0 :(得分:2)

Physics.Raycast()方法将方向作为第二个参数,而不是目标位置
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Debug.DrawLine()有效,因为它需要两个位置而不是位置和方向。

您可以像这样计算方向

Vector3 _shootTarget = new Vector3(_playerCharacter.transform.position.x, _playerCharacter.transform.position.y + _offSetY, _playerCharacter.transform.position.z);
Vector3 _direction = _shootTarget - this.transform.position;

答案 1 :(得分:0)

我知道这是非常古老的东西,但是我花了很长时间才弄清楚,任何形式的射线投射都将以非运动刚体和NAVMESH AGENT撞击与物体相连的对撞机,将导致极为不一致的命中。在这种情况下,刚体应该是运动学的。