checking line of sight with raycasts (2D)
i want to detect if a player is withing line of sight of an enemy. this is what i currently have(basically just did some guessing, cuz i don't understand raycasts )
RaycastHit2D hit;
hit = Physics2D.Raycast(transform.position, Player.transform.position - transform.position);
if (hit.collider.gameObject.tag == "Player"){
//do stuff
}
but this does not do anything. the //do stuff part never gets used, no matter if player is in line of sight or not.
Answer by bakir-omarov · Jun 12, 2018 at 04:45 PM
Hey! I think you are hitting own collider (collider of attached GameObject). For checking just add this line:
RaycastHit2D hit;
hit = Physics2D.Raycast(transform.position, Player.transform.position - transform.position);
if (hit.collider.gameObject.tag == "Player"){
Debug.Log("We found Target!");
}else
Debug.Log("I found something else with name = " + hit.collider.name);
And you will see (i hope) that you are hitting your own collider. For fixing, you can look there : https://answers.unity.com/questions/756380/raycast-ignore-itself.html
Your answer
Follow this Question
Related Questions
Best way to calculate damage of explosions 1 Answer
Line of sight for multiple targets - AI - in a 2d game 1 Answer
Line of Sight and Raycasting 0 Answers
Check if position is inside a collider 5 Answers
onMouseUp 2D Issues 0 Answers