0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ミサイルの軌道を描いて飛ばす処理の作り方:Unity2D

0
Posted at

この記事はUnityの文法や操作方法にある程度慣れてきた方向けです。


こんな感じでマウスで軌道を描いてオブジェクトを飛ばす処理を作ります。

サンプル.gif


応用すればこんなゲームが作れます。

サンプル1.gif

【ミサイルのソースコード】

/// <summary>
/// マウス操作でミサイルの軌道を描いて発射する処理
/// 1:クリックしたら軌道の描画開始 
/// 2:クリック中に軌道の保存 
/// 3:離したら移動開始 
/// 4:移動が終われば停止 
/// </summary>
public class MissileTrajectoryController : MonoBehaviour
{
    private enum State
    {
        Idle,
        Save,
        Flight
    }
    State currentState = State.Idle; // ミサイルの状態

    private Vector2 lastHistoryPos;  // 最後に追加したマウスの軌跡
    public float distanceStep;       // 軌道を更新する距離
    private Vector2 mouseWorldPos;   //マウスの座標

    private List<Vector2> historyPositions = new List<Vector2>(); // マウスの軌道の配列
    private int currentIdx = 0; // 現在の目標位置の要素番号
    public float flightSpeed; // 飛ぶ速さ

    public GameObject trajectoryPoint; //軌道を見る用の点オブジェクト

    void Start()
    {

    }

    void Update()
    {
        UpdateMousePosition();

        switch (currentState)
        {
            case State.Idle:
                CheckSaveStart();
                break;

            case State.Save:
                SaveMouseTrajectory();
                break;

            case State.Flight:
                Flight();
                break;

            default:
                break;
        }

    }

    /// <summary>
    /// マウスのワールド座標を更新
    /// </summary>
    void UpdateMousePosition()
    {
        mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    /// <summary>
    /// マウスの左クリックを押すと軌道の保存を開始する
    /// </summary>
    void CheckSaveStart()
    {
        if (Input.GetMouseButtonDown(0))
        {
            currentState = State.Save;
            lastHistoryPos = mouseWorldPos;
            historyPositions.Add(mouseWorldPos);
            Instantiate(trajectoryPoint, mouseWorldPos, Quaternion.identity);
        }
    }

    /// <summary>
    /// マウスの軌道を記録
    /// </summary>
    void SaveMouseTrajectory()
    {
        // マウスを話したら飛行状態に
        if (Input.GetMouseButtonUp(0))
        {
            currentState = State.Flight;
            return;
        }

        // マウスが移動したら軌道を配列に追加する
        if (Input.GetMouseButton(0))
        {
            float distance = Vector2.Distance(mouseWorldPos, lastHistoryPos);
            if (distance >= distanceStep)
            {
                historyPositions.Add(mouseWorldPos);
                lastHistoryPos = mouseWorldPos;

                Instantiate(trajectoryPoint, mouseWorldPos, Quaternion.identity);
            }
        }
    }

    /// <summary>
    /// 保存した軌道を元に飛行する
    /// </summary>
    void Flight()
    {
        Vector2 targetPos = historyPositions[currentIdx];
        transform.position = Vector2.MoveTowards(transform.position, targetPos, flightSpeed * Time.deltaTime);

        if (Vector2.Distance(transform.position, targetPos) < 0.01f)
        {
            currentIdx++;

            // 全ての配列を回ったら配列を初期化しアイドル状態に戻る
            if (currentIdx >= historyPositions.Count)
            {
                currentIdx = 0;
                historyPositions.Clear();
                currentState = State.Idle;
            }
        }
    }

}

【軌道確認の緑の点のスクリプト】

public class DeletePoint : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Destroy(gameObject);
    }
}

後はUnity側でこれらのスクリプトをアタッチして、
必要な変数とコライダーとリジッドボディを設定するだけです。

今回は等速移動するだけですが、加速や減速、墜落の動きを作ると一気にミサイルっぽくなってきます。

【注意】

マウスの入力検知と座標取得部分のコードがUnity5までの描き方のため、

Unity6で動作させる場合はプロジェクトの設定を変更するかコードを変える必要があります。

[プロジェクトの設定変更]

Edit → Project Settings → Player → Other Settings → Active Input Handling

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?