I'm making a FPS game, and I'm trying to write a method which detects when the enemy can see me. I do this using raycasts.
I have an issue where the raycast is not always hitting the (huge) box collider I expect it to always hit.
The raycast happens from my AIShooting script, and I expect it to hit the box collider of my character.
The AIShooting script looks like this:
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);
}
}
}
I make the raycast visible with a Debug.Drawline()
, and it looks like this.
The ray is shot from the character on the right to the character on the left (with the huge box collider).
However, the line Debug.Log("THE ENEMY SEES YOU");
is only triggered when I'm really, really close to the enemy character, and even then, it happens on certain locations and not consistent at all.
Thanks in advance!