# Raycast check for Collisions across XZ coords without Y rotations / Unity C#

I'm really new to Unity/C# (I have a bit of experience in GML but far from professional) and I am currently building out my first prototype.

I originally copied THIS script to get a cube that rotates face-to-face along one of its bottom edges.

Currently, the state of the game is the cube "rolling" around on a 10x10 grid. The grid currently has a border of walls. I want the cube to shoot a rayCast in the direction the cube is moving towards, check if there is a wall, and decide whether the cube can move in that direction.

This is the way I had it set up previously:

Vector3 up = new Vector3(0, 0, 0.5f);
Vector3 right = new Vector3(.5f, 0, 0);
Vector3 down = new Vector3(0, 0, -0.5f);
Vector3 left = new Vector3(-.5f, 0, 0);
Vector3 currentDirection = Vector3.zero;

bool Valid()
{
Ray myRay = new Ray(transform.position + currentDirection, transform.forward);
RaycastHit hit;

Debug.DrawRay(myRay.origin, myRay.direction, Color.red);
if (Physics.Raycast(myRay, out hit, rayLength))
{
if (hit.collider.tag == "Wall")
{
return false;
}
}
return true;
}


currentDirection is set to when movement keys "WASD" are pressed. I know one issue that I am running into is that transform.forward does not work because the Y-rotation of my cube never changes.

Gif format not supported so heres a link showcasing the problem: Movement & Clipping: https://i.imgur.com/XxlEx1G.gifv

Overall, I was wondering how to get the raycast to shoot in the appropriate direction based on movement.

Sorry if the answer is incredibly easy and I'm just missing it. Thanks for the help, Kalfin

• What is "the appropriate direction"? What rule would you use to define that direction? Once you articulate this, translating that rule into code should be reasonably straightforward. – DMGregory Feb 12 at 20:34

As you mention, transform.forward can't be used like that for a rotating cube -- you need to pass one of four different directions:

bool DirectionIsFree(Vector3 direction)
{
Ray ray = new Ray(transform.position, direction);
Debug.DrawRay(ray.origin, ray.direction, Color.red);
return !Physics.Raycast(ray, out RaycastHit hit, rayLength) ||
hit.collider.tag != "Wall";
}


The direction would now be absolute as per your world view, not relative to the cube transform. For instance, you'd now call

Vector3 desiredDirection = Vector3.zero;
if (Input.GetKeyDown(KeyCode.W))
{
desiredDirection = up;
}
else if (Input.GetKeyDown(KeyCode.A))
{
desiredDirection = down;
}

if (desiredDirection != Vector3.zero)
{
if (DirectionIsFree(desiredDirection))
{
MoveInDirection(desiredDirection);
}
else
{
PlayCannotDoSound();
}
}


Good luck!

• Worked perfectly! Thank you for the insight :) – Kalfin Feb 12 at 21:19