我正在尝试进行一次线播,以避免我的敌人从地图上掉下来并卡在墙上,如果他发现边缘或墙壁,他会翻转并开始向另一个方向移动。用于检测边缘的线路播放做得很好,但是面向左侧的线阵(检测墙壁)总是被触发,我不知道为什么,所以敌人只是不停地翻转每一帧。
我的剧本:
public class Enemy1 : MonoBehaviour {
Rigidbody2D myBody;
Transform myTransf;
public LayerMask enemyMask;
float myWidth;
public float speed;
// Use this for initialization
void Start () {
myTransf = this.transform;
myBody = this.GetComponent<Rigidbody2D>();
myWidth = this.GetComponent<SpriteRenderer>().bounds.extents.x;
}
// Update is called once per frame
void FixedUpdate () {
// checking if theres any walls or edges, if so, flip
Vector2 lineCastPos = myTransf.position - myTransf.right * myWidth;
Debug.DrawLine(lineCastPos, lineCastPos + Vector2.down);
bool isGrounded = Physics2D.Linecast(lineCastPos, lineCastPos + Vector2.down, enemyMask);
Debug.DrawLine(lineCastPos, lineCastPos - myTransf.right.toVector2() *0.1f);
bool isBlocked = Physics2D.Linecast(lineCastPos, lineCastPos - myTransf.right.toVector2() * 0.1f, enemyMask);
RaycastHit2D hit = Physics2D.Linecast(lineCastPos, lineCastPos - myTransf.right.toVector2());
if (!isGrounded || !isBlocked)
{
Vector3 currRot = myTransf.eulerAngles;
currRot.y += 180;
myTransf.eulerAngles = currRot;
Debug.Log("Ray Hit: " + hit.point);
}
//moving left always
Vector2 myVel = myBody.velocity;
myVel.x = -myTransf.right.x * speed;
myBody.velocity = myVel;
}
}
注意:RayCastHit2D Log给我的点0.0,0.0(在我的截图中的红点中突出显示)并且没有任何东西坐在那里,只有主摄像头。enter image description here