ray casting problem

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)

You’re not testing for whether the ray hits the player object first, so if the player’s in front of the shield, the raycast passes through the player until it hits the wall. I’d use a tag for the player, and check
(hit.gameObject.CompareTag (“player”)) first.

2 ron
I’d suggest you to use the Linecast function instead of Raycast because of it’s ability to cast the ray from one point to another (from a weapon to a player), so you can see if the ray hits the player or another object.

2 polytropoi and VladK - thanks for your replies. Really appreciate it!

I only tried out Linecast and it sorted out the problem.