Search code examples
unity-game-engineunityscript

Unity type racer


I'm designing a typeracer game in unity where the player is in an athletics 100m sprint and the faster they type, the faster the character runs.

I'm just wondering should I be aiming to get an animation that completes between every correct letter entered or working out an algorithm that speeds up, slows down and pauses the animation depending on whether the letter is correct.

Has anyone had any experience with something like this before? Also, being quite new to unity i'm just using the standard assets with Ethan as my model, is this the right thing to be doing here?


Solution

  • Original Thoughts

    You could have it so that every correct character type speeds up the animation of the character and slowly ticks down per millisecond that passes (i.e slowing down if you aren't typing). Then when the user enters a wrong character the animation gets increasingly slower (1/10 of the previous time every time (?)).

    Solution

    In Unity, working with timing is a little difficult, my class and I had issues with it this year. The best solution we found is working within the FixedUpdate loop itself, as this is run on a more concise time frame than just Update.

    Example

    For my solution (and what we all ended up doing) was to update the time in FixedUpdate and use it in Update

    void FixedUpdate() {
        if (timer >= 12f) stopped = true;
        if (!stopped) timerDT = updateTimer(Time.deltaTime);
    }
    

    If the timer variable is greater than 12 (seconds) then stop movement. If not stopped, continue updating and adding to the timer, as well as giving the frame time back to timerDT

    void Update() {
        this.transform.translate(velocity * timerDT);
    }
    

    This will run and update the game object attached based on its velocity and the time frame given in FixedUpdate

    For you, I would have the script save the animation controller as a variable in the script:

    Controller animation = {animation controller};
    

    Note: Don't remember what needs to go here, but I'm pretty sure it's the controller

    Then you can change the animation like so:

    void Update() {
        update_animation(timerDT, anim_speed);
    }
    
    void FixedUpdate() {
        timerDT = updateTimer(Time.deltaTime);
        if (timerDT - oldDT > 0.1) {
            oldDT = timerDT;
            anim_speed = anim_speed / 0.1; // for decreasing speed
        }
    }
    
    void update_animation(float deltatime, float speed) {
        animation["run"].speed = anim_speed;
    }