Slighty different approach with Jump

Hi there,
it’s been a while since I did something in the 2D course and so I would like to post my approach on the particle system.

(Maybe someone would like to add a jump function at this point.)

Since I previously added the jump function, I already had a check to see if the player is grounded, so I used that instead of creating a new script.

Take care. :beers:

Here is my code so far:

public class PlayerController : MonoBehaviour
{
    [SerializeField] float torqueAmmount = 1f;
    [SerializeField] float boostSpeed = 30f;
    [SerializeField] float breakSpeed = 10f;
    [SerializeField] float baseSpeed = 20f;
    [SerializeField] float jumpForce = 2f;
    [SerializeField] float xJump = 0f;
    [SerializeField] float yJump = 2f;
    [SerializeField] ParticleSystem rideEffect;
    Rigidbody2D rb2d;
    SurfaceEffector2D surfaceEffector2D;
    bool isGrounded;
    Vector2 jump;

    // Start is called before the first frame update
    void Start()
    {
        // Get the Rigidbody2D component and store it in rb2d
        rb2d = GetComponent<Rigidbody2D>();
        surfaceEffector2D = FindObjectOfType<SurfaceEffector2D>();
        jump = new Vector2(xJump, yJump);
    }

    // Update is called once per frame
    void Update()
    {
        PlayRideEffect();
        RotatePlayer();
        ChangeSpeed();
        AddJump();
    }

    // PlayRideEffect checks if isGrounded and plays effect if true else stops playing the effect
    void PlayRideEffect()
    {
        if (isGrounded)
        {
            rideEffect.Play();
        }
        else
        {
            rideEffect.Stop();
        }
    }

    // AddJump ads an Impulse to make player jump when pressing "space" key
    void AddJump()
    {
        if (Input.GetKey(KeyCode.Space) && isGrounded)
        {
            rb2d.AddForce(jump * jumpForce, ForceMode2D.Impulse);
            isGrounded = false;
        }
    }

    // OnCollisionStay2D sets isGrounded to true if player is touching the Surface Effector 2D
    void OnCollisionStay2D(Collision2D other) {
        isGrounded = true;
    }

    // ChangeSpeed changes speed if arrow key up/down is pressed
     void ChangeSpeed()
    {
        if (Input.GetKey(KeyCode.UpArrow))
        {
            surfaceEffector2D.speed = boostSpeed;
        } else if (Input.GetKey(KeyCode.DownArrow))
        {
            surfaceEffector2D.speed = breakSpeed;
        } else
        {
            surfaceEffector2D.speed = baseSpeed;
        }
    }

    // AddTorque adds torque
    void AddTorque(float torque)
    {
        rb2d.AddTorque(torque);
    }

    // RotatePlayer adds rotation when arrow key l/r is pressed
    void RotatePlayer() 
    {
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            AddTorque(torqueAmmount);
        } else if (Input.GetKey(KeyCode.RightArrow))
        {
            AddTorque(-torqueAmmount);
        }
    }
}

1 Like

Privacy & Terms