#实现接触地面时跳跃
private bool isground;
[SerializeField] private float groundcheck;
[SerializeField] private LayerMask whatisground;
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position,new Vector3(transform.position.x,transform.position.y-groundcheck));
}
OnDrawGizmos的DrawLine方法可以绘画一条线段
可以看到这条线的起始点为现有位置,终止点为向下距离为-groundcheck的点
这样可以显示在场景上,便于调整
update中输入:
isground=Physics2D.Raycast(transform.position,Vector2.down,groundcheck,whatisground);
transform.position
:表示射线的起点,通常是当前物体的位置。Vector2.down
:表示射线的方向,这里是向下的方向,即垂直向下。groundcheck
:表示射线的长度或检测距离,即射线会延伸多远进行碰撞检测。whatisground
:表示射线会与哪些层进行碰撞检测,只有在指定的层上的物体才会被检测到碰撞。
当线段与gound层(unity中指定gound为whatisground)接触时,isground为true,反之为false
private void jump()
{
if(isground)
rb.velocity = new Vector2(rb.velocity.x, jumpa);
}
添加到jump方法中