- Home /
Can someone help me to understand why this raycast is not working properly?
RaycastHit hit;
var rayDirection = Player.transform.position - Enemy.transform.position;
Debug.DrawRay(transform.position, rayDirection);
if (Physics.Raycast(transform.position, rayDirection, out hit)) {
if (hit.collider.gameObject.tag == "Player"){
Debug.Log("Works");
}
else {
}
}
This code is inside of the update function. Basically, the ray is drawn in the right position, but the Debug.Log("Works"); is never printed into the console. I am trying to make this so the enemy will only shoot at the player when they are in direct line of sight.
Thanks for the help!
Also if someone could help me so the ray would stop when it came in contact with one of the walls, that would be a big help!
Are you sure the player is tagged with "Player" and does the player have any colliders attached? Also what is Enemy here? And by the way, the ray will stop at the first thing it hits.
To follow up with some of the other responses here, I think you should give yourself a bit more diagnostic information. For example:
if (Physics.Raycast(transform.position, rayDirection, out hit))
{
Debug.Log("Raycast hit: " + hit.collider.gameObject.tag);
// ...
}
Answer by Etherpod · Jun 30, 2021 at 07:07 PM
Did you add the "Player" tag to the object you're shooting?
Your answer
Follow this Question
Related Questions
How to stop enemies from shooting each other 1 Answer
Shooting and damage with raycast doesnt work. 0 Answers
Shotgun raycast 1 Answer
Player Raycast Does Not Compute 0 Answers
can foe hear us? 1 Answer