Quest: Hide & Seek Coroutines Quest
Challenge: One For The Road
Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.
Quest: Hide & Seek Coroutines Quest
Challenge: One For The Road
Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.
There are quite a few Coroutines running is this mini One For The Road game
Couldn’t think of any good ideas for this challenge, but here is how my HideAI script turned out in the end.
public class HideAI : MonoBehaviour
{
// configs
[SerializeField] float minRunDistance = 5f;
[SerializeField] float maxRunDistance = 100f;
// state
Vector3 hidingSpot;
// Unity messages
IEnumerator Start()
{
// When found, calculate a random hiding spot from player's current position, then move to that position.
// (Calculation may occur over a number of frames to reduce load.)
// Doesn't seek a new hiding spot until it's reached the currently targeted hiding spot and then found.
NavMeshAgent agent = GetComponent<NavMeshAgent>();
while (true)
{
yield return new WaitUntil(() => CanBeSeenByPlayer(transform.position));
yield return StartCoroutine(SetHidingSpot(minRunDistance, maxRunDistance));
agent.SetDestination(hidingSpot);
yield return new WaitUntil(() => !NavMeshAgentIsMoving());
}
}
// private methods
IEnumerator SetHidingSpot(float minDistance, float maxDistance)
{
Vector3 sampleSpot;
do
{
float randomDistance = Random.Range(minDistance, maxDistance);
Vector2 randomPosition = Random.insideUnitCircle * randomDistance;
Vector3 randomOffset = new Vector3(randomPosition.x, 0, randomPosition.y);
sampleSpot = transform.position + randomOffset;
yield return null;
}
while (CanBeSeenByPlayer(sampleSpot) ||
!NavMesh.SamplePosition(sampleSpot, out NavMeshHit hit, transform.position.y + .01f, NavMesh.AllAreas));
hidingSpot = sampleSpot;
}
bool NavMeshAgentIsMoving()
{
NavMeshAgent agent = GetComponent<NavMeshAgent>();
return agent.pathPending || agent.remainingDistance > 0;
}
bool CanBeSeenByPlayer(Vector3 point)
{
Vector3 direction = point - Camera.main.transform.position;
float distance = direction.magnitude;
if (Physics.Raycast(Camera.main.transform.position, direction, distance))
{
return false;
}
return true;
}
}
I purchased a Meta ‘Oculus’ Quest 2 at the end of Feb after seeing lots of Unity jobs advertising for VR skills.
Four weeks later and I’ve released a Virtual Reality version of my Balloon Hunt I created here for this quest… Basic with still lots to learn…