Part5:Collision Check (P32)
1:效果和操作
效果:地面检测,墙体检测,只有当player位置和地面图层的距离一定是才能idle和run
基本操作:给人物添加wallcheck墙体检测和groundcheck地面检测,利用Physics2D.Raycast检测人物上的wallcheck是否于与地面在特定距离内拥有碰撞,以此来作为move和jump以及air状态之间的转化
2:代码改变
//Player代码改变
//即为a➡️b,check表示a,distance表示a和b的距离,b表示目的地
[Header("Collision Info")]
[SerializeField] private Transform groundCheck;//用于定义人物地面检测的出发点
[SerializeField] private float groundCheckDistance;//地面检测的距离
[SerializeField] private Transform wallCheck;//用于定义人物墙体检测的出发点
[SerializeField] private float wallCheckDistance;//墙体检测的距离
[SerializeField] private LayerMask whatIsGround;//目的地所在图层
public bool IsGroundDetected()//地面检测
{
return Physics2D.Raycast(groundCheck.position, Vector2.down, groundCheckDistance, whatIsGround);
}//表示从groundcheck的位置出发,向下(down)以groundCheckDistance的距离检测是否与whatIsGround对应的object物体存在碰撞
//该方法可以简写为
//public bool IsGroundDetected()=>Physics2D.Raycast(groundCheck.position, Vector2.down, groundCheckDistance, whatIsGround);
private void OnDrawGizmos()//画线便于观察
{
Gizmos.DrawLine(groundCheck.position, new Vector3(groundCheck.position.x, groundCheck.position.y - groundCheckDistance
Gizmos.DrawLine(wallCheck.position, new Vector3(wallCheck.position.x + wallCheckDistance, wallCheck.position.y ));
}
//PlayerGroundState代码改变
public override void Update()
{
base.Update();
if (Input.GetKeyDown(KeyCode.Space)&&player.IsGroundDetected())
//只有按下空格和人物目前在地面上才能转化为jumpstate
{
stateMachine.ChangeState(player.jumpState);
}
}
//PlayerAirState代码改变
public override void Update()
{
base.Update();
if (player.IsGroundDetected())
//当处于air状态时于地面接触,严格意义上为射线发生碰撞,即转为idle状态
{
stateMachine.ChangeState(player.idleState);
}
}
3:效果图