简体   繁体   中英

Player not jumping. Unity RigidBody2D

When I press my jump key, the player doesn't jump but the Debug message I added does print in console.

My code:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    // Start is called before the first frame update

    private Transform transform;
    private Rigidbody2D rb;

    private bool onground = false;

    public float speed;
    public float momentum;
    public float jumpForce;
    void Start()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
        transform = rb.transform;
    }

    // Update is called once per frame
    void Update()
    {
    }

    private void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");

        Vector3 movement = new Vector3(moveHorizontal, 0, 0);

        transform.position += movement * Time.deltaTime * speed;

        if (Input.GetButtonDown("Jump") && onground)
        {
            Jump(jumpForce);
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Floor")
        {
            onground = true;
            Debug.Log("Player Is On Ground!");
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.collider.tag == "Floor")
        {
            onground = false;
            Debug.Log("Player Is Not On The Ground!");
        }
    }

    private void Jump(float force)
    {
        rb.velocity = Vector2.up * force * Time.deltaTime;
        Debug.Log("Player Has Jumped!");
    }
}

the player can move but not jump and haven't found any posts anywhere with a similar issue, I might not be looking hard enough or searching the correct thing but I just cannot find a solution to my problem.

First of all, you move the player by transform component but trying to jump by physics ( rigidbody ), it isn't a good idea and I recommend you to work only with rigidbody in this case. Also the multiply jump force by Time.deltaTime doesn't have a sense because you call the method from FixedUpdate() , I assume that the power of jump is too week to see the result so try to remove Time.deltaTime and increase the jumpForce value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM