unity isGrounded 工作疯狂

unity isGrounded works crazy

嗨创作者我正在尝试制作我的第一款 3d 游戏所以一切顺利告诉我今天什么时候我决定改变运动脚本 我正在检查玩家是否在附加到玩家的空游戏对象上使用 OnTriggerEnter(Collider coll) 接地并且它工作正常并且玩家像我梦见的那样移动 'but' 在测试变量 isGrounded 时进行一些随机移动后变为 false即使玩家被禁足了我确信的事情 所以她是我在 gameObject child

上使用的代码
using System.Collections.Generic;
using UnityEngine;

public class isGrounded : MonoBehaviour
{
   public bool isgrounded=false;

   private void OnTriggerEnter(Collider col){

      isgrounded=true;
   }

   private void OnTriggerExit(Collider col){

      isgrounded=false;
   }
} 

和玩家移动脚本

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moves : MonoBehaviour
{    


    GameObject cam,world;
    Rigidbody rd;
    bool moveR,moveL,jump,teleport;
    
    // Start is called before the first frame update
    void Start()
    {
       rd=GetComponent<Rigidbody>();
       cam=GameObject.Find("Main Camera"); 
       world=GameObject.Find("World"); 
      
    }

    // Update is called once per frame
    void Update()
    {   
        if(Input.GetKeyDown(KeyCode.D)){
            moveR=true;
            
        } if(Input.GetKeyUp(KeyCode.D)){
            moveR=false;
        }
        if(Input.GetKeyDown(KeyCode.A)){
            moveL=true;
            
        }if(Input.GetKeyUp(KeyCode.A)){
            moveL=false;
        }
        if(Input.GetKeyDown(KeyCode.Space)){
            jump=true;
        }
        if(Input.GetKeyUp(KeyCode.Space)){
            jump=false;
        }
        if(Input.GetKeyDown(KeyCode.W)){
           teleport=true;
           world.GetComponent<Rigidbody>().velocity=new Vector3(0,0,-90);
        }

    }

    void FixedUpdate(){ Debug.Log(isGrounded());
        

        if(moveR==true&&isGrounded()==true){ 
                rd.velocity=new Vector3(5,0,0);
                if(jump==true){rd.velocity+=new Vector3(0,5f,0);}
                }
        
        if(moveL==true&&isGrounded()==true){ 
                rd.velocity=new Vector3(-5,0,0);
                if(jump==true){rd.velocity+=new Vector3(0,5f,0);}
                }
             

        if(jump==true&&isGrounded()==true){ 
                rd.velocity+=new Vector3(0,5f,0);
         }
}


    bool isGrounded(){
     return transform.Find("GroundCheck").GetComponent<isGrounded>().isgrounded;
    }    
       
}

我真的很想知道为什么,并确保我理解这个美妙的变量 isGrounded 在玩家被禁足时变为假的机制 我还想知道 OnTriggerEnter 和 OnTriggerStay

之间是否存在差异

问题是您正在通过 OnTriggerEnter 和 OnTriggerExit 检查对象是否接地。

您无法使用此方法正确确定。相反,您应该使用 https://docs.unity3d.com/ScriptReference/Physics.Raycast.html。您可以向下投掷 Raycast,检查它是否击中了任何具有与您的地面物体相对应的标签的东西,如果是,那么您就知道您在地面上。

对于第二个问题。 OnTriggerEnter 和 OnTriggerStay 之间的区别在于 OnTriggerEnter 仅在一个碰撞体进入另一个碰撞体时被调用。另一方面,如果碰撞体相互重叠,OnTriggerStay 会不断被调用。