Home > Net >  Unity 3d How to reset a counter on a trampoline when you stop bouncing
Unity 3d How to reset a counter on a trampoline when you stop bouncing

Time:08-16

I started coding with unity and C# a week ago so forgive me if this is a dumb question.

I have made a trampoline in unity, the player jumps on it and it bounces the player up, higher each time using simple if statements and a counting integer.

My playerController script is set in the unity inspector. The trampoline acts as intended, it's working fine.

However, I would like it if the player would reset their momentum after leaving the trampoline and touching the ground.

Currently, after leaving the trampoline and getting back on it, they are bouncing as high as they were when they left it. So the counting integer needs to be reset.

I thought to do this with a simple check of the players "isgrounded" function and if true reset the trampolines jumpCount to 0.

But this isn't working. I have no idea why. To me, it seems like it should. The isgrounded is evaluating to true but the "else if (playerFP.groundCheck == true)" isnt activating.

Heres my code:

public class Trampoline : MonoBehaviour
{
    public PlayerMovement1stPerson playerFP;
    [SerializeField] int jumpCount = 0;

    private void OnTriggerEnter(Collider collision) 
    { 
        if (jumpCount == 0 && collision.gameObject.tag == "Player" )
        {
            Debug.Log("Bounce 1 activated");
            playerFP.velocity.y = 5;
            jumpCount   ;
        }

        else if (jumpCount == 1 && collision.gameObject.tag == "Player")
        {
            playerFP.velocity.y = 10;
            jumpCount   ;
        }
        
        else if (jumpCount == 2 && collision.gameObject.tag == "Player")
        {
            playerFP.velocity.y = 15;
            jumpCount   ;
        }

        else if (jumpCount >= 3 && collision.gameObject.tag == "Player")
        {
            Debug.Log("Max Bounce");
            playerFP.velocity.y = 15;
        }
        
        else if (playerFP.groundCheck == true)
        {
            Debug.Log("Bounces reset");
            jumpCount = 0;
        }
    }
}

I'd really appreciate any tips.

CodePudding user response:

Your bouncing (and ground check code) is being ran inside the Trampoline's OnTriggerEnter method. This means that the check will ONLY happen when the player enters the trampoline's trigger, not when the player lands on any ground.

Move the if check outside of the OnTriggerEnter method. The Update() method inside the Trampoline script would work, but the cleanest implementation would be to store the bouncing information within the player, rather than each trampoline instance. (That also allows a player to bounce on multiple trampolines without losing the height between them)

  • Related