# Using raycast to detect whether a wall immediately blocks a player in Unity C#

I am working on a game project of which involves a procedurally generated maze. Within this maze, there are different types of tiles, such as walls and gates. I want to program the player so that it cannot move through a tile that is tagged as a "wall", and I am hoping to use ray casting to detect item tags. Now, you may think it would be simpler to use rigid bodies, but the game is set up so that the player moves 1 unit per movement, instead of being able to move at any randomly input distance, in order to keep the game adhering to a "grid" for the sake of other events that happen within the game.

So, for this reason, i wish to detect if a wall is north of the player (let's call "north" as "up", as I have an "up blocked" boolean to state if a wall is directly "north" of the player) but, my code doesn't always recognise walls that are immediately north of the player, and instead sometimes the "up blocked" boolean becomes activated as "true" when a wall is left, right, or "below" (down) of the player, irrespective of whether or not there is a wall "above" or down.

here is my code:

Vector2 vUp = new Vector2(transform.position.x, (transform.position.y + 0.05f));

RaycastHit2D hitUp = Physics2D.Raycast(transform.position, vUp);

if (hitUp.collider != null && hitUp.collider.tag == "wall")  {
upBlocked = true;
} else {
upBlocked = false;
}


I have spent many hours looking for a solution for this problem, but most mediums provide information that either didn't work, wasn't applicable or simply was grossly out of date.

When in doubt, check the docs for the methods you're using.

Physics2D.Raycast takes an origin position and a direction, but you're passing it an origin and a destination

If you want to check 0.05 units up on the y axis, try...

float rayDistance = 0.05f;

Physics2D.Raycast(
transform.position,
Vector2.up,
rayDistance
);

• thank you very much, it works perfectly, for 2 reasons: as my code is now also more readable since I don't have to use separate vectors such as "vUp". – AntonyBoys Mar 26 '18 at 11:36
• Don't forget to mark the answer with an "Accepted" checkmark if it solved the issue. – DMGregory Mar 26 '18 at 13:35