Unity刚体穿过条件,模仿《GRIS》楼梯效果,可从下方穿过

  • 知识点
  • 碰撞器和触发器

触发信息检测:
1.MonoBehaviour.OnTriggerEnter(Collider other) / MonoBehaviour.OnTriggerEnter2D(Collider2D other)当进入触发器
2.MonoBehaviour.OnTriggerExit(Collider other) / MonoBehaviour.OnTriggerExit2D(Collider2D other)当退出触发器
3.MonoBehaviour.OnTriggerStay(Collider other) / MonoBehaviour.OnTriggerStay2D(Collider2D other)当逗留触发器

碰撞信息检测:
1.MonoBehaviour.OnCollisionEnter(Collision collisionInfo) / MonoBehaviour.OnCollisionEnter2D(Collision2D collisionInfo)当进入碰撞器
2.MonoBehaviour.OnCollisionExit(Collision collisionInfo) / MonoBehaviour.OnCollisionExit2D(Collision2D collisionInfo)当退出碰撞器
3.MonoBehaviour.OnCollisionStay(Collision collisionInfo) / MonoBehaviour.OnCollisionStay2D(Collision2D collisionInfo) 当逗留碰撞器

物体初始设置为触发器
挂载物体脚本的核心部分:

private void OnCollisionEnter2D(Collision2D col)
{
    rig = col.gameObject.GetComponent<Rigidbody2D>();
    if (col.gameObject.tag == "Player")
    {
        if (rig.gameObject.transform.position.y < gameObject.transform.position.y) 
        gameObject.GetComponent<PolygonCollider2D>().isTrigger = true;
    }
}

private void OnCollisionExit2D(Collision2D col)
{
    if (col.gameObject.tag == "Player")
    {
        gameObject.GetComponent<PolygonCollider2D>().isTrigger = true;
    }
}

private void OnTriggerEnter2D(Collider2D col)
{
    rig = col.gameObject.GetComponent<Rigidbody2D>();
    if (col.gameObject.tag == "Player")
    {
        if (rig.velocity.y <0 || rig.gameObject.transform.position.y > gameObject.transform.position.y) 
        gameObject.GetComponent<PolygonCollider2D>().isTrigger =false ;
    }
}

基本可以实现效果,有更好的方法欢迎大神补充。

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页