I’m trying to implement an enemy weapon in my game. I want the weapon to fire at my player as long as the player is not protected by an obstacle.
I’m using ray casting to implement this. Each obstacle has a layer assigned to it. I assigned User Layer 8 and called it “Shield”. Using the “Physics.Raycast” function I can check if the ray that is cast between the weapon and the player hits an obstacle.
To test my implementation I draw a white line between the weapon and the player if the player is not protected by an obstacle. If there is an obstacle between the player and the weapon I draw a yellow line between the obstacle and the weapon. The yellow and white line can be seen in the Scene window.
I implemented a simple example (see attachment). The player can walk around on a plane and there’s a wall in the centre of the plane which is the obstacle the player can hide behind. The weapon is an empty GameObject with an attached script called WeaponScript. This script implements the ray casting.
The WeaponScript works well if there is a clear line between the weapon and the player (i.e. a white line is drawn between the weapon and the player). It also works if the player hides behind the wall (i.e. a yellow line is drawn between the weapon and the wall).
But there’s one problem I noticed: When the player stands very close in front of the wall where there is a clear line between the player and the weapon, a yellow line is drawn which means that the player is protected. This shouldn’t happen since there’s clear line between the weapon and the player. A white line should be drawn.
Can anyone tell me what I can do the fix this problem?
112335–4314–$test_shield_169.zip (8.69 MB)