繁体   English   中英

我正在尝试使用 unity 制作游戏,但我的 Jump 功能不起作用

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

我正在尝试按照教程制作简单的 2D 游戏,当我做与教程相同的事情时,我的跳跃功能不起作用,左右移动功能起作用,请在下面帮助我,我附上了我的源代码和相关屏幕截图

我的播放器类

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);

问题可能是您选择的Ground层的 LayerMask 被忽略,因此IsGrounded函数将返回 false。

您想要做的是在统一编辑器中选择您希望 Raycast 忽略的图层(我假设除Ground之外的所有图层),然后再试一次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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