我正试图让一些游戏对象在迷宫中随机走动。我目前正常工作,对象可以向左/向右/向前。我遇到的问题是当有机会前进和左/右时总是选择左转或右转,他们从不选择前进,我无法弄清楚为什么......我在这里缺少什么?
public float speed;
public bool changed = false;
public bool forward, left, right;
protected Transform frontRaycast, leftRaycast, rightRaycast;
void Update(){
if(!changed){
forward = Physics2D.Linecast(transform.position, frontRaycast.position, 1 << LayerMask.NameToLayer("Wall"));
left = Physics2D.Linecast(transform.position, leftRaycast.position, 1 << LayerMask.NameToLayer("Wall"));
right = Physics2D.Linecast(transform.position, rightRaycast.position, 1 << LayerMask.NameToLayer("Wall"));
List<int> possibleDirs = new List<int>();
if(!forward){
possibleDirs.Add(0);
}
if(!left){
possibleDirs.Add(1);
}
if(!right){
possibleDirs.Add(2);
}
int dir = 0;
//Debug.Log(Random.Range(0, possibleDirs.Count));
if(possibleDirs.Count > 0){
dir = (int)possibleDirs[Random.Range(0, possibleDirs.Count)];
}
Debug.Log(dir);
switch(dir){
case 0:
transform.Rotate(new Vector3(0,0,0));
break;
case 1:
transform.Rotate(new Vector3(0,0,90));
changed = true;
Invoke("reset", 0.5f);
break;
case 2:
transform.Rotate(new Vector3(0,0,-90));
changed = true;
Invoke("reset", 0.5f);
break;
}
}
transform.Translate(Vector2.right * Time.deltaTime * speed);
}
void reset(){
changed = false;
}