Подсчитайте, кто пересек финишную черту первым (C # UNITY) - PullRequest
0 голосов
/ 14 февраля 2019

Я уже решил таймер и записал время того, кто пересекает финишную черту.Но я не знаю, как рассчитать, кто первым пересечет финишную черту.Может кто-нибудь подсказать мне, вот мой код

public float timer = 0f;

float currentTimeBot1 = 0f;
float currentTimeBot2 = 0f;
float currentTimeBot3 = 0f;
float currentTimeBot4 = 0f;
float currentTimeBot5 = 0f;
float currentTimePlayer = 0f;

float bestTime = 0f;

bool first, second, third, startrace, finishrace;

public GameObject startCountDown;

private void Start()
{
    //startrace = true;
    StartCoroutine(waitForTheCountdown());
}

private void Update()
{
    if (startrace)
    {
        timer += Time.deltaTime;
    }
    else
    {
        timer = 0f;
    }

}

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Bot1"))
    {
        Debug.Log("Bot1 Finished");
        currentTimeBot1 = timer;
        Debug.Log(currentTimeBot1.ToString());
    }

    if (other.gameObject.CompareTag("Bot2"))
    {
        Debug.Log("Bot2 Finished");
        currentTimeBot2 = timer;
        Debug.Log(currentTimeBot2.ToString());
    }

    if (other.gameObject.CompareTag("Bot3"))
    {
        Debug.Log("Bot3 Finished");
        currentTimeBot3 = timer;
        Debug.Log(currentTimeBot3.ToString());
    }

    if (other.gameObject.CompareTag("Bot4"))
    {
        Debug.Log("Bot4 Finished");
        currentTimeBot4 = timer;
        Debug.Log(currentTimeBot4.ToString());
    }

    if (other.gameObject.CompareTag("Bot5"))
    {
        Debug.Log("Bot5 Finished");
        currentTimeBot5 = timer;
        Debug.Log(currentTimeBot5.ToString());
    }

    if (other.gameObject.CompareTag("Player"))
    {
        Debug.Log("Player Finished");
        currentTimePlayer = timer;
        Debug.Log(currentTimePlayer.ToString());
    }


}

private IEnumerator waitForTheCountdown()
{
    yield return new WaitForSeconds(6f);
    if (startCountDown.GetComponent<StartCountdown>().raceStarted == true)
    {
        startrace = true;
    }
    else
    {
        startrace = false;
    }
}

Я пробовал такую ​​формулу, но она слишком длинная и работает только в некоторых случаях

if(currentTimePlayer > currentTimeBot1 || currentTimePlayer > currentTimeBot2 || currentTimePlayer > currentTimeBot3 || currentTimePlayer > currentTimeBot4 || currentTimePlayer > currentTimeBot5){
       Debug.Log("1st!");
}

1 Ответ

0 голосов
/ 14 февраля 2019

Я бы просто сохранил их все в списке (и обычно использовал бы if-else или, может быть, даже switch-case для лучшей производительности)

public List<GameObject> winners = new List<GameObject>();

private void OnTriggerEnter(Collider other)
{
    switch(other.gameObject.tag)
    {
        case "Bot1":
            Debug.Log("Bot1 Finished");
            currentTimeBot1 = timer;
            Debug.Log(currentTimeBot1.ToString());
            break;

        case "Bot2":
            Debug.Log("Bot2 Finished");
            currentTimeBot2 = timer;
            Debug.Log(currentTimeBot2.ToString());
            break;

        case "Bot3":
            Debug.Log("Bot3 Finished");
            currentTimeBot3 = timer;
            Debug.Log(currentTimeBot3.ToString());
            break;

        case "Bot4":
            Debug.Log("Bot4 Finished");
            currentTimeBot4 = timer;
            Debug.Log(currentTimeBot4.ToString());
            break;

        case "Bot5":
            Debug.Log("Bot5 Finished");
            currentTimeBot5 = timer;
            Debug.Log(currentTimeBot5.ToString());
            break;

        case "Player":
            Debug.Log("Player Finished");
            currentTimePlayer = timer;
            Debug.Log(currentTimePlayer.ToString());
            break;

        default:
            return;
    }

    // this is only matched if one of the before tags matched
    winners.Add(other.gameObject);
}

Таким образом, вы не только получаете первого победителя(winners[0]), но на самом деле вы можете получить весь порядок, в котором они закончили, например,

for(var i = 0; i< winners.Count; i++)
{
    Debug.LogFormat("{0}. {1}", i + 1, winners[i].name);
}

Если вам также нужно время окончания, а не использовать словарь, такой как

public Dictionary<GameObject, float> winners = new Dictionary<GameObject, float>();

private void OnTriggerEnter(Collider other)
{
    switch(other.gameObject.tag)
    {
        case "Bot1":
            winners.Add(other.gameObject, timer);
            break;
    }

    // ...

    Debug.Log(other.gameObject.tag + " Finished");
    Debug.Log(winners[other.gameObject].ToString());
}

снова получите доступ к каждому из них, например

var winner = winners[0].key;
var bestTime = winners[0].value;

, или выполните итерацию по всем победителям

foreach(var kvp in winners)
{
    var winner = kvp.key;
    var finishTime = kvp.value;
    //...
}

или получите доступ к определенному времени окончания GameObjects

var finishTime = winners[aCertainGameObject];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...