简体   繁体   中英

I'm try to make game using unity and my Jump functionality not working

I'm trying to make simple 2D game following tutorials when I did same thing as tutorial my jump functionality not working and left and right move functionality working please help me below I attached my source code and relevant screen shot

my player class

public class Player : MonoBehaviour
{
    private Rigidbody2D _rigid;
    //variable for jump
    [SerializeField]
    private float _jumpForce = 5.0f;
    [SerializeField]
    private LayerMask _grondLayer;
    private bool _resetJump = false;

    // Start is called before the first frame update
    void Start()
    {
        _rigid = GetComponent<Rigidbody2D>();
    }

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

    void Movement()
    {
        float move = Input.GetAxisRaw("Horizontal");
        _rigid.velocity = new Vector2(move,_rigid.velocity.y);
        if(Input.GetKeyDown(KeyCode.Space) && IsGrounded()==true)
        {
            Debug.Log("jump");
            _rigid.velocity = new Vector2(_rigid.velocity.x,_jumpForce);
            StartCoroutine(ResetJumpNeededRoutine());
        }
    }

    bool IsGrounded()
    {
        RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, _grondLayer);
        if(hitInfo.collider != null)
        {
            if(_resetJump==false){return true;}
        }
        return false;
    }

    IEnumerator ResetJumpNeededRoutine()
    {
        _resetJump = true;
        yield return new WaitForSeconds(0.1f);
        _resetJump = false;
    }

}

在此处输入图片说明

在二维字符上实现跳转机制的正确方法。

_rigid.AddForce(new Vector2(0, _jumpForce), ForceMode2D.Impulse);

The problem is probably the LayerMask you selected Ground layer to be ignored therefore IsGrounded function will return false.

What you wanna do is select the layers you'd like your Raycast to ignore (All except Ground I assume) in the unity editor then give it another go.

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