I have a Bug class which I’m trying to make shoot at the player only when it has line of sight. The debug rays render correctly, but the physical rays never hit anything (collider is null).
public class Bug : MonoBehaviour
{
public int health;
public GameObject spit;
float prevRotationY;
public int fireDelay;
public GameObject player;
protected static System.Random random = new System.Random();
// Start is called before the first frame update
void Start()
{
spit = GameObject.Find("Spit");
}
// Assumes that this object has a child object "Body"
public virtual void Update()
{
Rigidbody rigidbody = GetComponent<Rigidbody>();
if (DroneControl.sessionActive)
{
Collider[] colliders = Physics.OverlapCapsule(transform.position, transform.position + new Vector3(0, 5, 0), 20);
foreach (Collider item in colliders)
{
if (item.gameObject.tag == "Player")
{
Collider enemyCollider=GetComponent<Collider>();
Ray ray = new Ray(transform.position,item.gameObject.transform.position-transform.position);
Debug.DrawRay(transform.position, item.gameObject.transform.position - transform.position,Color.green);
RaycastHit rayHit;
enemyCollider.Raycast(ray,out rayHit, 1000);
Debug.Log(rayHit.collider);
//if (rayHit.collider == item.gameObject.GetComponent<BoxCollider>())
{
player = item.gameObject;
prevRotationY = transform.rotation.eulerAngles.y;
Quaternion quaternion = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(transform.position - item.transform.position), 0.5f);
transform.rotation = quaternion;
if (Math.Abs(prevRotationY - transform.rotation.eulerAngles.y) < 0.5f)
{
//Shoot();
}
}
//else Debug.Log(item.gameObject.GetComponent<BoxCollider>()+" + "+rayHit.collider);
break;
}
}
if (player != null)
{
if (Vector3.Distance(transform.position, player.transform.position) > 20)
{
if (RotateTowards(player))
{
rigidbody.AddRelativeForce(Vector3.back * 100f, ForceMode.Impulse);
}
}
}
//increase velocity loss
rigidbody.velocity /= 2;
}
if (health <= 0)
{
Destroy(gameObject);
}
}
/*
* Returns: whether this object's rotation is aligned to the target
*
*/
bool RotateTowards(GameObject gameObject)
{
float prevRotation = transform.rotation.eulerAngles.y;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(transform.position - gameObject.transform.position), 0.01f);
return Math.Abs(prevRotation - transform.rotation.eulerAngles.y) < 0.1;
}
public virtual void Shoot()
{
}
}