编程语言
首页 > 编程语言> > Unity3D C#学习之路(六)C# 下蹲

Unity3D C#学习之路(六)C# 下蹲

作者:互联网

BoxCollider2D coll;
Vector2 collStandSize, collStandOffset, collCrouchSize, collCrouchOffset;
Vector2 headRayPos, headOffset;
bool isCrouch;
Public LayerMask groundLayer;  //吧地面拖进来,别忘了给地面加一个专属的Layer

void Start()
{
    coll = GetCompent<BoxCollider2D>();
    collStandSize = coll.size;    //获取一开始的碰撞体大小
    collStandOffset = coll.offset;    //获取一开始的碰撞体位置
    collCrouchSize = new Vector2(coll.size.x, coll.size.y / 2);  //获取下蹲时候的碰撞体大小
    collCrouchOffset = new Vector2(coll.offset.x, coll.offset.y / 2);    //获取下蹲时候的碰撞体位置
    headOffset = new Vecotr2(0f, coll.size.y);    //偏移量
    headRayPos = transform.position + headOffset;    //头顶的位置
}

void FixedUpdate()
{
    Crouch();    //下蹲函数
}

void PhysicsCheck()
{
    RaycastHit2d headCheck = Raycast(headRayPos, Vector2.up, 0.1f, groundLayer);    //在头顶上创建一个长度为0.1的射线
    if(headCheck)
        StandUp();  //调用站立函数
}

void Crouch()
{
    if(Input.GetButton("Crouch"))
    {
        isCrouch = true;
        coll.size = collCrouchSize;
        coll.offset = collCrouchOffset;
    }
}

void StandUp()
{
    coll.size = collStandSize;
    coll.offset = collStandOffset;
    isCrouch = false;
}

RaycastHit2D Raycast(Vecotr2 offset, Vector2 rayDiraction, float length, LayerMask layer)
{
    RaycastHit2D hit = Physics2D.Raycast(offset, rayDiraction, length, layer);
    return hit;
}

 

标签:Unity3D,collStandOffset,C#,Vector2,学习,coll,offset,void,size
来源: https://www.cnblogs.com/yunligig/p/15092262.html