How to move and jump with Rigidbody2D in Unity

Remember to attach Rigidbody2D and Collider2D components to your character.

In order to make your character jump and fall more dynamic change Gravity Scale to higher value.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    [SerializeField] float jumpForce = 3500f;
    [SerializeField] float moveSpeed = 10f;
    Rigidbody2D rb;
    float dirX;
    bool jumpBtnPressed = false;
    bool isGrounded = false;
    void Start() {
        rb = GetComponent<Rigidbody2D>();
    }
    void Update() {
        dirX = Input.GetAxisRaw("Horizontal");
        if(Input.GetButtonDown("Jump") && isGrounded){
            jumpBtnPressed = true;
        }
    }

    void FixedUpdate(){
        rb.velocity = new Vector2(moveSpeed * dirX, rb.velocity.y);
        if(jumpBtnPressed){
            rb.AddForce(new Vector2(0f,jumpForce),ForceMode2D.Impulse);
            jumpBtnPressed = false;
            isGrounded = false;
        }
    }

    void Move(int direction){
        dirX = direction;
    }

    void Jump(){
        if(isGrounded){
            jumpBtnPressed = true;
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *