Created
September 4, 2017 19:40
-
-
Save joduplessis/d2282736dc3d41bdd0d9fe26f9e06d84 to your computer and use it in GitHub Desktop.
Strategy for implementing self driving cars (objects) in Unity 3D. This is very taxing on the CPU as it essentially uses computer vision in the game world sense.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RaycastHit hit; | |
bool foundRoad = false; | |
bool playerIsInFront = false; | |
Vector3 current = new Vector3(gameObject.transform.position.x, 5, gameObject.transform.position.z); | |
Vector3 aheadWorld = new Vector3(0, -5, 15); | |
Vector3 leftWorld = new Vector3(-15, -5, 0); | |
Vector3 rightWorld = new Vector3(15, -5, 0); | |
Vector3 behindWorld = new Vector3(0, -5, -15); | |
Vector3 ahead = gameObject.transform.TransformDirection(aheadWorld); | |
Vector3 left = gameObject.transform.TransformDirection(leftWorld); | |
Vector3 right = gameObject.transform.TransformDirection(rightWorld); | |
Vector3 behind = gameObject.transform.TransformDirection(behindWorld); | |
Debug.DrawRay(current, ahead); | |
Debug.DrawRay(current, left); | |
Debug.DrawRay(current, right); | |
Debug.DrawRay(current, behind); | |
// If there is road ahead | |
if (Physics.Raycast (current, ahead, out hit)) { | |
if (hit.collider.gameObject.tag == "Player") { | |
playerIsInFront = true; | |
} else { | |
if (!foundRoad && isRoad (hit.collider.gameObject)) { | |
transform.LookAt (hit.collider.gameObject.transform.position); | |
foundRoad = true; | |
} | |
} | |
} | |
// If there is road to the left | |
if (Physics.Raycast (current, left, out hit)) { | |
if (!playerIsInFront && !foundRoad && isRoad (hit.collider.gameObject)) { | |
transform.LookAt(hit.collider.gameObject.transform.position); | |
foundRoad = true; | |
} | |
} | |
// If there is road to the right | |
if (Physics.Raycast (current, right, out hit)) { | |
if (!foundRoad && isRoad (hit.collider.gameObject)) { | |
transform.LookAt(hit.collider.gameObject.transform.position); | |
foundRoad = true; | |
} | |
} | |
// If there is road behind | |
if (Physics.Raycast (current, behind, out hit)) { | |
if (!foundRoad && isRoad (hit.collider.gameObject)) { | |
transform.LookAt(hit.collider.gameObject.transform.position); | |
foundRoad = true; | |
} | |
} | |
// Look at the road | |
if (foundRoad && !playerIsInFront) { | |
if (!gm.paused) { | |
gameObject.transform.position += gameObject.transform.TransformDirection (Vector3.forward) * 5.0f * Time.deltaTime; | |
} | |
} | |
if (!foundRoad) { | |
gm.deleteObject (gameObject); | |
gm.createRandomCar (); | |
} | |
private bool isRoad(GameObject g) { | |
if (g.tag == "Road") { | |
return true; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment