スペースシューター作りの練習11
2014年1月22日〜2月2日にかけて書いた、Unity HP のチュートリアル II 1 〜 17を復習しています。
今回は、17の続きです。敵機がPlayerに的を絞らせないような動きをさせる(回避戦術)スクリプトの追加です。
<新敵機と回避戦術スクリプトの追加> EnemyをEnemy1にリネーム後、複製してEnemy2とリネーム。Enemy2にEvasiveManeuver.cs追加します。数値は図のように設定。

<落下物のサイズを増やす> GameController選択後、Hazards Sizeを4に変更。Element3にEnemy2をドロップ。
<回避戦術スクリプトEvasiveManeuver.cs> やはり、私のチープな頭では難しく、いいかげんな解釈です
。
using UnityEngine;
using System.Collections;
//回避的戦術
public class EvasiveManeuver : MonoBehaviour
{
public Boundary boundary; //Boundary
public float tilt; //傾き角度
public float dodge; //身をかわす度合い
public float smoothing; //スムーズ(?)
public Vector2 startWait; //戦術前の待ち時間
public Vector2 maneuverTime; //戦術実行時間
public Vector2 maneuverWait; //戦術後待ち時間
private float currentSpeed; //現在速度
private float targetManeuver; //回避戦術ベクトル(X方向)
void Start ()
{
currentSpeed = rigidbody.velocity.z; //Z方向現在速度
StartCoroutine(Evade()); //Evade()へ
}
IEnumerator Evade ()
{
yield return new WaitForSeconds (Random.Range (startWait.x, startWait.y)); //戦術前待ち時間
while (true)
{
targetManeuver = Random.Range (1, dodge) * -Mathf.Sign (transform.position.x); //回避戦術ベクトル
yield return new WaitForSeconds (Random.Range (maneuverTime.x, maneuverTime.y)); //戦術実行時間
targetManeuver = 0; //初期化
yield return new WaitForSeconds (Random.Range (maneuverWait.x, maneuverWait.y)); //戦術後待ち時間
}
}
void FixedUpdate ()
{
float newManeuver = Mathf.MoveTowards (rigidbody.velocity.x, targetManeuver, smoothing * Time.deltaTime); //新ベクトル
rigidbody.velocity = new Vector3 (newManeuver, 0.0f, currentSpeed); //新速度(X方向移動)
//新ポジション設定(Boundaryによる縛りあり)
rigidbody.position = new Vector3
(
Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax)
);
rigidbody.rotation = Quaternion.Euler (0, 0, rigidbody.velocity.x * -tilt); //Z軸回転(機体を傾ける)
}
}
<コマンドのことなど>・yield return new WaitForSeconds (Random.Range (a, b)) … aからbの間のランダムな秒数時間待ち
・Mathf.Sign(数値) … sinの値を返す
※後の追記:「Mathf.Sign(a)は、aが正か0の時1を返し、負の時は-1を返す」の間違いでした。 三角関数のSinの場合は、Mathf.Sin(a) です。<(_ _)>
・Mathf.MoveTowards … よく分かりませんが、Referenceでは、
static float MoveTowards(float current, float target, float maxDelta);
----------
Parameters
current
The current value.
target
The value to move towards.
maxDelta
The maximum change that should be applied to the value.
----------
とあります。現在の値から最大変化値で目指す値に向かう時の値(意味が分かりませんが)、ってかんじでしょうか。分かったような分からないような感じです。
以上は私の勝手な解釈です。間違っている可能性大ですので、参考程度でお願いします。
で、プレイしてみると、とても難しく、すぐやられてしまいます。難易度高過ぎ!
とにかく、最後まで行きました。
----------------- <ご注意>私自身が全くの超初心者ですので、文中まちがいがあるかも知れません。その際はご容赦をお願いします。<(_ _)>