如何阻止玩家部分穿过地面

时间:2019-07-28 12:48:55

标签: c# unity3d

我为2D角色制作了一个控制器,我修复了玩家在墙上晃动的问题,但无法解决玩家在地面上晃动的问题。从多个教程和调整内容中获得了此代码。如果您有任何值得赞赏的技巧,那么我是新手,并致力于我的第一款游戏(不得不漫步,因为我投入了太多代码)。

{
    public float speed, height;
    Rigidbody2D rb;
    private bool horizontalRight = false;
    private bool horizontalLeft = false;
    private bool verticalMove = false;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }



    void Update()
    {
        if (Input.GetAxisRaw("Horizontal") > 0)
        {
            horizontalRight = true;
        }
        else if (Input.GetAxisRaw("Horizontal") < 0)
        {
            horizontalLeft = true;
        }
        if (Input.GetButton("Jump") && rb.velocity.y == 0)
        {
            verticalMove = true;

        }

    }

    private void FixedUpdate()
    {
        if (horizontalRight == true)
        {
            transform.Translate(Vector2.right * Time.deltaTime * speed);
            horizontalRight = false;
        }
        else if (horizontalLeft == true)
        {
            transform.Translate(Vector2.left * Time.deltaTime * speed);
            horizontalLeft = false;
        }
        if (verticalMove == true)
        {
            rb.velocity = new Vector2(0, height);
            verticalMove = false;

        }
    }


}    

2 个答案:

答案 0 :(得分:0)

典型的团结跳跃看起来像:

void Jump()
{
    if (_isGrounded == true)
    {
        rb.AddForce(Vector2.up * _jumpSpeed);
        _isGrounded = false;
    }
}

以及发生碰撞事件

void OnCollisionEnter (Collision hit)
{
    _isGrounded = true;
}

这将限制您何时可以使用跳转。

答案 1 :(得分:0)

激活刚体上的连续碰撞检测功能,只要它们通过速度移动,就可以防止它们逐步移相。