Movement script with addForce has inconsistent values.

If I move up and then back down, there will be 3 random outcomes:

Why does this happens?

I am making Frogger game so I need those values to be consistent.

void ReadInput()
    {
        if(!isJumping)
        {
            if (keyMap.c.moveUp.WasPerformedThisFrame()) TriggerJump(new Vector2(0, 1), 0);
            if (keyMap.c.moveRight.WasPerformedThisFrame()) TriggerJump(new Vector2(1, 0), -90);
            if (keyMap.c.moveDown.WasPerformedThisFrame()) TriggerJump(new Vector2(0, -1), 180);
            if (keyMap.c.moveLeft.WasPerformedThisFrame()) TriggerJump(new Vector2(-1, 0), 90);
        }
    }

    void TriggerJump(Vector2 direction, float facing)
    {
        Debug.Log("trigger Jump");
        moveDirection = direction;
        transform.eulerAngles = Vector3.forward * facing;
        anim.Play("Jump");
        StartCoroutine(JumpDuration());
    }

    void Jump()
    {
        if (isJumping) rb.AddForce(moveDirection * jumpStrength, ForceMode2D.Impulse);
    }

    IEnumerator JumpDuration()
    {
        KinematicToggle();
        isJumping = true;
        yield return new WaitForSeconds(jumpDuration);
        KinematicToggle();
        isJumping = false;
    }

    public void KinematicToggle()
    {
        rb.velocity = Vector2.zero;
        if (rb.isKinematic == true) rb.isKinematic = false;
        else rb.isKinematic = true;
    }

Don’t use physics for frogger. That’s the problem. Physics is just not appropriate. Just sequence the moves and check the collision yourself. For something cel-like with frogger it’s trivial to tween between possible locations.

Source: I wrote this game for Nintendo Wii:

https://www.youtube.com/watch?v=K0CatpyJ16w

1 Like