2017年12月1日 星期五

思考如何試圖抓住目標對象的程式設計




這個腳本(Enemy.cs)在需要敵方物體跟隨玩家或者其他想要瞄準的物體時很有用。 當敵人朝著目標物體(上圖中白色物體)移動時,敵人(Enemy)產生跳躍效應。 看起來好像敵人自己在思考,像是有點具備人工智慧(AI)的感覺,敵人可以思考行動路徑試圖抓住目標對象。

程式解析如下:

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);

沒有留言:

張貼留言