I have a level with tiles of 1 unit each. How do I make sure that the player(lavender) never goes into the walls and always stays in the middle of the walkable area(steel blue) ?
I have tried to put nodes(red) which, if hit by a raycast ray will allow the turn to happen, but this method fails when the player is at a high speed.
Check the level image here:
Check my code here:
RaycastHit hit;
Ray wRay;
Ray aRay;
Ray sRay;
Ray dRay;
void Update () {
transform.position += transform.forward * speed * Time.deltaTime;
if (Input.GetKey (KeyCode.W)) {
wRay.origin = transform.position;
wRay.direction = Vector3.left;
if (Physics.Raycast(wRay, out hit, 2f) && hit.transform.tag == "turnallowed")
{
gameObject.transform.rotation = Quaternion.Euler(0,270,0);
}
Debug.DrawRay(transform.position, Vector3.left, Color.red);
}
if (Input.GetKey (KeyCode.A)) {
aRay.origin = transform.position;
aRay.direction = Vector3.back;
if (Physics.Raycast(aRay, out hit, 2f) && hit.transform.tag == "turnallowed")
{
gameObject.transform.rotation = Quaternion.Euler(0,180,0);
}
Debug.DrawRay(transform.position, Vector3.back, Color.blue);
}
if (Input.GetKey (KeyCode.S)) {
sRay.origin = transform.position;
sRay.direction = Vector3.right;
if (Physics.Raycast(sRay, out hit, 2f) && hit.transform.tag == "turnallowed")
{
gameObject.transform.rotation = Quaternion.Euler(0,90,0);
}
Debug.DrawRay(transform.position, Vector3.right, Color.white);
}
if (Input.GetKey (KeyCode.D)) {
dRay.origin = transform.position;
dRay.direction = Vector3.forward;
if (Physics.Raycast(aRay, out hit, 2f) && hit.transform.tag == "turnallowed")
{
gameObject.transform.rotation = Quaternion.Euler(0,0,0);
}
Debug.DrawRay(transform.position, Vector3.forward, Color.green);
}
}
