【问题标题】:Unity Tag and Collider problem while player is jumping玩家跳跃时的 Unity Tag 和 Collider 问题
【发布时间】:2019-06-07 05:18:50
【问题描述】:

这是我的播放器的跳转代码:

void Update()
{
    float oldmoveHorizontal = moveHorizontal;
    moveHorizontal = Joystick.Horizontal;
    moveVertical = Joystick.Vertical;    

    if (isJumping == false && moveVertical >= .7f)
    {
        moveVertical = Speed * 70;
        isJumping = true;
    }

    ball_move = new Vector2(moveHorizontal, moveVertical);         
    ball_rigid.AddForce(ball_move);

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Ground")
         {
             isJumping = false;
         }        
    }
}

当球接触到对撞机下方时,它可以再次跳跃。我怎样才能阻止这种情况?

如果无法下载:https://ibb.co/yVgXmrM

【问题讨论】:

    标签: c# unity3d collider


    【解决方案1】:

    一种解决方案是检查碰撞的碰撞点的位置,并查看它们中的任何一个距离玩家的中心“足够低”以成为可跳跃的碰撞:

    private Collider2D playerCollider; 
    private float playerJumpableOffset = 0.001;
    
    void Start() { playerCollider = GetComponent<Collider2D>(); }
    
    void OnCollisionEnter2D(Collision2D col)
    {
        float jumpableWorldHeight = transform.position.y - playerJumpableOffset;
    
        for (int i = 0 ; i < col.contactCount && isJumping; i++)  
        {
            Vector2 contactPoint = col.GetContact(i).point; 
            if (contactPoint.y <= jumpableWorldHeight) 
            {
                isJumping = false;
            }
        }
    }
    

    【讨论】:

    • 感谢您的帮助!
    【解决方案2】:
    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Ground")
        {
            foreach (ContactPoint2D item in col.contacts)
            {
                Debug.Log("Normal:" + item.normal);
                if (item.normal.y > 0 && col.gameObject.tag == "Ground")
                {
                    isJumping = false;
                    Debug.Log("Top of Collider");
                }
            }
        }}
    

    我通过检查对撞机的顶部找到了我的解决方案。 使用这种代码方式,如果玩家触摸到对撞机的顶部,它将再次激活跳跃。

    【讨论】:

    • 检查ContactPoint2D.normal.y的好主意!!这比我的答案要好:) 当stackoverflow允许你时,你应该选择它作为最佳答案
    • 您也可以尝试不同的方法。您可以在玩家模型的脚上设置一个点,而不是检查玩家是否击中某物来确定他是否在跳跃,您可以从该点对地面图层蒙版执行Physics.CheckSphere() 以确定玩家是否站在地面上。
    猜你喜欢
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    相关资源
    最近更新 更多