检测左边和右边是否有地面
老师的代码写的是有问题的,见我扩展的代码
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class PhysicsCheck : MonoBehaviour
{
private CapsuleCollider2D coll;
[Header("监测参数")]
public bool manual;
public Vector2 bottomOffset;
public Vector2 bottomLeftOffset;
public Vector2 bottomRightOffset;
public Vector2 leftOffset;
public Vector2 rightOffset;
public float checkRaduis;
public LayerMask groundLayer;
[Header("状态")]
public bool isGround;
public bool isLeftGround;
public bool isRightGround;
public bool touchLeftWall;
public bool touchRightWall;
private void Awake()
{
coll = GetComponent<CapsuleCollider2D>();
//if (!manual)
//{
// rightOffset = new Vector2(coll.offset.x + coll.bounds.size.x / 2, coll.bounds.size.y / 2);
// leftOffset = new Vector2(coll.offset.x - coll.bounds.size.x / 2, coll.bounds.size.y / 2);
//}
}
void Update()
{
Check();
}
public void Check()
{
if (!manual)
{
int faceDir = 0;
if (transform.localScale.x > 0)
{
faceDir = 1;
}
else if (transform.localScale.x < 0)
{
faceDir = -1;
}
bottomOffset = new Vector2(faceDir * coll.offset.x, coll.bounds.size.y / 2 - coll.offset.y);
bottomLeftOffset = new Vector2(faceDir * coll.offset.x - coll.bounds.size.x / 2, coll.bounds.size.y / 2 - coll.offset.y);
bottomRightOffset = new Vector2(faceDir * coll.offset.x + coll.bounds.size.x / 2, coll.bounds.size.y / 2 - coll.offset.y);
leftOffset = new Vector2(faceDir * coll.offset.x - coll.bounds.size.x / 2, coll.bounds.size.y / 2);
rightOffset = new Vector2(faceDir * coll.offset.x + coll.bounds.size.x / 2, coll.bounds.size.y / 2);
}
// 监测地面
isGround = Physics2D.OverlapCircle((Vector2)transform.position + bottomOffset, checkRaduis, groundLayer);
isLeftGround = Physics2D.OverlapCircle((Vector2)transform.position + bottomLeftOffset, checkRaduis, groundLayer);
isRightGround = Physics2D.OverlapCircle((Vector2)transform.position + bottomRightOffset, checkRaduis, groundLayer);
// 墙体判断
touchLeftWall = Physics2D.OverlapCircle((Vector2)transform.position + leftOffset, checkRaduis, groundLayer);
touchRightWall = Physics2D.OverlapCircle((Vector2)transform.position + rightOffset, checkRaduis, groundLayer);
}
private void OnDrawGizmosSelected()
{
// 绘制监测区
Gizmos.DrawWireSphere((Vector2)transform.position + bottomOffset, checkRaduis);
Gizmos.DrawWireSphere((Vector2)transform.position + bottomLeftOffset, checkRaduis);
Gizmos.DrawWireSphere((Vector2)transform.position + bottomRightOffset, checkRaduis);
Gizmos.DrawWireSphere((Vector2)transform.position + leftOffset, checkRaduis);
Gizmos.DrawWireSphere((Vector2)transform.position + rightOffset, checkRaduis);
}
}
这段代码在运行起来之后,就会出现左、右、左下、右下、下共五个检测盒,并且能判断左边、右边、左下、右下、下是否有地面
即使野猪转向了,检测盒的范围也是正确的
野猪撞墙后等待几秒再修改方向
项目相关代码
代码仓库:https://gitee.com/nbda1121440/2DAdventure.git
标签:撞墙,野猪,Vector2,bounds,transform,coll,计时,public,size From: https://www.cnblogs.com/hellozjf/p/18031579