向いている方向に角度が近い敵に向かって射撃(自動照準)

向いている方向に撃つのではなく、向いている方向に角度が近い敵に対して、
弾を撃つ(自動照準)
弾丸は予め100個生成されていて、再利用している
撃つ時に誰が撃ったかを記録しておいて、衝突時に、撃った人に加点する

if (Input.GetKey (KeyCode.Space)) {
   float minAngle=1000;
   ZombieController other;
   for (int i=0; i<100; i++) {
       if (Main.objZ [i] == null)
           continue;
       other = Main.objZ [i].GetComponent<ZombieController> ();
       if (other.ActiveFlag == false)
           continue;
       Vector3 forward = transform.TransformDirection(Vector3.forward);
       Vector3 targetDirection = Main.objZ [i].transform.position - transform.position;
   
       float angle = Vector3.Angle(forward, targetDirection);
       if(angle<minAngle)
       {
           minAngle=angle;
           targetObj=Main.objZ [i];
       }
   }
   transform.LookAt (targetObj.transform);

   GameObject BulletObj = Main.objB [Main.bno];
   BulletObj.GetComponent<Rigidbody>().velocity = Vector3.zero;
   BulletObj.GetComponent<Renderer>().enabled = true;
   BulletObj.transform.position=this.transform.position;
   BulletObj.transform.LookAt (targetObj.transform);

   BulletObj.transform.Translate( new Vector3(0,1.15f,0.6f) );
   BulletObj.GetComponent<Bullet>().Owner=this.gameObject;//弾丸の持ち主を記録
   BulletObj.GetComponent<Bullet>().ActiveFlag=true;
   BulletObj.GetComponent<Rigidbody>().AddForce(BulletObj.transform.forward*1);
   Main.bno++;if (Main.bno >= 100) Main.bno = 0;

   AllMotionOff ();
   animator.SetBool ("Gun", true);
   myTimer  = 0.5f;
   myTimer2 = 2.8f;
   status =Main.getStatus ("SHOOT");
}

予め弾丸を100個生成して配列に入れておく

GameObject b_Prefab5 = (GameObject)Resources.Load("Bullet"); 
objB=new GameObject[100];
for (int j=0; j<100; j++) {
  objB [j] = GameObject.Instantiate (b_Prefab5, Vector3.zero, Quaternion.identity) as GameObject;
  objB [j].GetComponent<Renderer>().enabled = false;
}
bno = 0;

タグ:

unity
最終更新:2015年05月26日 19:27