前回、敵(タレット)を作成したので、攻撃のバリエーションを増やす為にもミサイルを追加します。
ミサイルスクリプトでは以下の処理をする。
・移動処理(目標に一定角速度以下で回転しながら巡行)
・衝突を検知したら削除★
・有効時間経過で失速し落下★
・ダメージ等必要な情報を渡したり渡されたり★
★の部分は以前作成した弾丸スクリプトと同じなので、
継承を使いたいと思います。
親クラスとしてShotクラス、
その子クラスにBulletクラス、Missileクラスといった感じに作成します。
以下のようになりました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
public class Shot : MonoBehaviour { public float speed = 100; public int effectiveTime = 30; public float damage = 100; protected int elapsedTime = 0; protected Vector3 movementSpeed; void Start () { Rigidbody rigidbody = GetComponent<Rigidbody>(); movementSpeed = new Vector3 (0,0,speed); rigidbody.velocity = transform.rotation * movementSpeed; elapsedTime = effectiveTime; } void OnCollisionEnter(){ Destroy (this.gameObject); } public void Create(float damage,float speed,int effectiveTime){ this.speed = speed; this.damage = damage; this.effectiveTime = effectiveTime; } void Update () { elapsedTime--; } protected void OutRange(){ if (elapsedTime <= 0) { Rigidbody rigidbody = GetComponent<Rigidbody>(); rigidbody.drag = 0.2f; Vector3 tmpSpeed = rigidbody.velocity; tmpSpeed.y -= 0.8f; rigidbody.velocity = tmpSpeed; transform.rotation = Quaternion.LookRotation (tmpSpeed); if (elapsedTime <= -300) { Destroy (this.gameObject); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : Shot { public void Create(float damage,float speed,int effectiveTime){ this.speed = speed; this.damage = damage; this.effectiveTime = effectiveTime; } void Update () { elapsedTime--; OutRange (); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Missile : Shot { public GameObject target; protected float rotateSpeed = 1f; public void Create(float damage,float speed,int effectiveTime,float rotateSpeed,GameObject target){ this.speed = speed; this.damage = damage; this.effectiveTime = effectiveTime; this.rotateSpeed = rotateSpeed; this.target = target; } void Update () { elapsedTime--; Rigidbody rigidbody = GetComponent<Rigidbody>(); if (elapsedTime > 0) { //角度修正 if (target != null) { float dis = Vector3.Distance (this.transform.position, target.transform.position); Vector3 targetDir = target.transform.position - transform.position; float step = rotateSpeed * Time.deltaTime; Vector3 newDir = Vector3.RotateTowards (transform.forward, targetDir, step, 10.0F); transform.rotation = Quaternion.LookRotation (newDir); rigidbody.velocity = transform.rotation * movementSpeed; } } else { /*誘導時間が終了した場合*/ OutRange (); } } } |
以下のようにミサイルタレットを作成できました。
コメント