- Home /
Issue with Raycasts in Unity 2D
using UnityEngine;
using System.Collections;
public class EnemySight: MonoBehaviour
{
public GameObject player;
public float fovAngle;
public bool playerInSight;
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject == player)
{
Vector2 playerDir = other.transform.position - transform.position;
float angle = Vector3.Angle(playerDir, transform.right);
if (angle < fovAngle / 2)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, playerDir.normalized);
if (hit.collider.gameObject == player)
{
Debug.DrawRay(transform.position, playerDir.normalized, Color.green);
print("halp meh");
}
}
}
}
}
This is a script for an enemy view script for a 2d top down stealth game. The part that isn't working is the last bit involving the raycasts. Everything works up to the hit.collider.gameObject == player
. Nothing prints and the debug ray is not drawn. If I change it to hit.collider != null
it "works", but the raycasts hit the enemy itself. There are no actual errors, and the variables are all defined in-editor. Any help/comments are appreciated. Relatively new to Unity so it's probably a dumb mistake.
try to move 24th Line to somewhere above this condition:
if (hit.collider.gameObject == player)
Then take a look and see where the ray is going and to what object is hitting.
sorry if I had mistakes in my sentences im not native English speaker
Answer by gtaharaedmonds · Sep 13, 2016 at 06:44 AM
The reason it wasn't working is the ray was hitting the enemy (where the script was attached to). All I had to do was add a layer mask that ignored the enemy.
Answer by Bigiansen · Sep 12, 2016 at 09:43 PM
Instead of comparing the actual gameobject, set the layer for the player and compare that instead.
If your player collider is in a nested gameobject, the comparison will be false.
if(other.gameObject.layer == LayerMask.NameToLayer("Player"))
{
//...
}
Also try debugging the ray before any comparison is made:
Instead of this:
if (angle < fovAngle / 2)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, playerDir.normalized);
if (hit.collider.gameObject == player)
{
Debug.DrawRay(transform.position, playerDir.normalized, Color.green);
print("halp meh");
}
}
It should look like this:
if (angle < fovAngle / 2)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, playerDir.normalized);
Debug.DrawRay(transform.position, playerDir.normalized, Color.green);
if (hit.collider.gameObject == player)
{
print("halp meh");
}
}
Turns out the reason it wasn't working is the ray was hitting the enemy (where the script was attached to). All I had to do was add a layer mask that ignored the enemy. Thanks for the replay though.