Player in front of enemy check not working, Physics.Raycast()?
This the game scene with two use cases as follows:
The player cannot be seen by the enemy:
The player can be seen by the enemy:
I am using the following code to decide whether the line of vision between the player and the enemy is clear for the enemy to attack, i.e., the enemy should only attack when there is no wall or any other collider between the player and the enemy:
void playerInRangeOfEnemy()
{
// After checking player is in range of the enemy, check for the line of vision between them
Transform Player = FindObjectOfType<Player>().transform;
Vector2 rayDirection = Player.position - transform.position; // --> transform.position is of the enemy
RaycastHit hit;
if(Physics.Raycast(transform.position, rayDirection, out hit, minAttackDistance))
{
Debug.Log("Ray hitting the player"); // Not logging in either of the two cases mentioned above
if (hit.collider.gameObject.CompareTag("Player"))
{
// The following line is also not being logged
Debug.Log("Make the enemy attack the player");
}
}
}
Both the enemy and the player are dynamic Rigidbodies. minAttackDistance
is just the length of the raycast I want to cast, is set to 100 for now for testing.
How can I make the condition to be true so that both of the Logs are executed? Any updates to the above code?
Answer by xxmariofer · Dec 17, 2020 at 01:53 PM
Hello, are you using 3d object colliders for some reason? if not, you need to use the Physics2D method not the 3D one https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
Physics2D.Raycast(transform.position, rayDirection, out hit, minAttackDistance)
Your answer
Follow this Question
Related Questions
Physics Raycast not working 1 Answer
raycasthit to set new move location 0 Answers
About AI detecting a sound 1 Answer
Use raycast to change color 1 Answer