I am building a game like The line Zen. Player is moving along a road and has to avoid hitting the edges. Right now, i have planned it as follows: On click , cast rays in 8 directions. For the returned hit, perform movement. For e.g, if ray hits something on the right, and tag of that collider is “up”, player moves up & left (-1,1). If tag is “down”, player moves left and down (-1,-1).
Road objects have tags “up” and “down” to indicate whether player should move up or down on that road.
This is working on horizontal and vertical roads shown here:

But, does not work on diagonal roads shown here:

Code shown below:
public class PlayerController : MonoBehaviour {
float distance =0.5f;
public LayerMask lm;
RaycastHit2D up,down,left,right,ne,nw,se,sw;
Vector2 NE,NW,SE,SW;
// Use this for initialization
void Start () {
GetComponent<Rigidbody2D>().velocity=Vector2.right;
NE = new Vector2 (1, 1);
NW = new Vector2 (-1, 1);
SE = new Vector2 (1,-1);
SW = new Vector2 (-1, -1);
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0))
castRay ();
}
void castRay()
{
up = Physics2D.Raycast (transform.position,Vector2.up,0.5f,lm);
down = Physics2D.Raycast (transform.position, -(Vector2.up), 0.5f, lm);
right = Physics2D.Raycast (transform.position, Vector2.right, 0.5f,lm);
left = Physics2D.Raycast (transform.position, -(Vector2.right), 0.5f, lm);
ne=Physics2D.Raycast (transform.position, NE, 0.5f, lm);
nw=Physics2D.Raycast (transform.position, NW, 0.5f, lm);
se=Physics2D.Raycast (transform.position, SE, 0.5f, lm);
sw=Physics2D.Raycast (transform.position, SW, 0.5f, lm);
if (up.collider != null) {
GetComponent<Rigidbody2D>().velocity=new Vector2(1,-1);
}
else if (down.collider != null) {
GetComponent<Rigidbody2D>().velocity=new Vector2(1,1);
}
else if (left.collider != null) {
if(left.collider.tag=="up")
GetComponent<Rigidbody2D>().velocity=new Vector2(1,1);
else
GetComponent<Rigidbody2D>().velocity=new Vector2(1,-1);
}
else if (right.collider != null) {
if(right.collider.tag=="up")
{
Debug.Log("right hit");
GetComponent<Rigidbody2D>().velocity=new Vector2(-1,1);
}
else
GetComponent<Rigidbody2D>().velocity=new Vector2(-1,-1);
}
else if (ne.collider != null) {
if(ne.collider.tag=="up")
{
Debug.Log("ne hit");
GetComponent<Rigidbody2D>().velocity=new Vector2(-1,1);
}
else
GetComponent<Rigidbody2D>().velocity=new Vector2(-1,-1);
}
else if (nw.collider != null) {
if(nw.collider.tag=="up")
{
Debug.Log("right hit");
GetComponent<Rigidbody2D>().velocity=new Vector2(1,1);
}
else
GetComponent<Rigidbody2D>().velocity=new Vector2(1,-1);
}
else if (se.collider != null) {
if(se.collider.tag=="up")
{
Debug.Log("right hit");
GetComponent<Rigidbody2D>().velocity=new Vector2(-1,1);
}
else
GetComponent<Rigidbody2D>().velocity=new Vector2(-1,-1);
}
}
}
lm is the layermask assigned to “road” layers. How can I make it behave the same way on diagonal roads?