程式解析如下:
1.前面沒有障礙物
if (!isThereAnyThing) {
Vector3 relativePos = target.transform.position - transform.position;
Quaternion rotation = Quaternion.LookRotation (relativePos);
transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime);
}
2.往前移動
transform.Translate (Vector3.forward * Time.deltaTime * speed);
3.檢查前方有沒有障礙物,並使用Physics.Raycast()進行偵測
Transform leftRay = transform;
Transform rightRay = transform;
if (Physics.Raycast (leftRay.position + (transform.right * 7), transform.forward, range)) {
isThereAnyThing = true;
transform.Rotate (Vector3.up * Time.deltaTime * rotationSpeed);
}
if (Physics.Raycast (rightRay.position - (transform.right * 7), transform.forward, range)) {
isThereAnyThing = true;
transform.Rotate (Vector3.up * Time.deltaTime * rotationSpeed);
}
4.已經通過障礙物
if (Physics.Raycast (transform.position - (transform.forward * 4), transform.right, 10)) {
// Just making this boolean variable false it means there is nothing in front of object.
isThereAnyThing = false;
}
if (Physics.Raycast (transform.position - (transform.forward * 4), -transform.right, 10)) {
// Just making this boolean variable false it means there is nothing in front of object.
isThereAnyThing = false;
}
5.輸出除錯資訊
Debug.DrawRay (transform.position + (transform.right * 7), transform.forward * 20, Color.red);
Debug.DrawRay (transform.position - (transform.right * 7), transform.forward * 20, Color.red);
Debug.DrawRay (transform.position - (transform.forward * 4), - transform.right * 20, Color.yellow);
Debug.DrawRay (transform.position - (transform.forward * 4), transform.right * 20, Color.yellow);
沒有留言:
張貼留言