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_从零开始设计一个RPG游戏(8)网络通信系统-使用protobuffer实现前后端通信的网络模块


下一篇:[Unity3D]模型、美术资源集合,各种类型都有,不间断更新