LoginSignup
6
4

More than 5 years have passed since last update.

[Unity] 動かないオブジェクトの後ろに軌跡を出す

Last updated at Posted at 2018-04-27

自機が常に原点にいると何かと都合がよい、などの理由で、実は自分が止まっていてまわりが動いている、といった作り方をすることがあります。

2018-04-27_113233.png

そんな時、「動いている感」を出すために軌跡を表示したくても、TrailRenderer は自分が動いていないと軌跡を出してくれません。

そこで、LineRendererを使って自分の後ろに軌跡を作ってみます。

まずは軌跡のスタート地点となる空のオブジェクトを用意します。
そこにAdd Component > Effect > LineRendererをアタッチします

2018-04-27_112139.png

次に以下のスクリプトを同じオブジェクトにアタッチします

InvTrail.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InvTrail : MonoBehaviour {
    [SerializeField] float m_spd=10f;
    [SerializeField] int m_positionCount = 50;
    LineRenderer m_lr;
    Vector3[] m_oldPos;
    int m_cnt;

    // Use this for initialization
    void Start () {
        m_lr = GetComponent<LineRenderer>();
        if (!m_lr)
            Destroy(this);

        m_lr.positionCount = m_positionCount;
        m_oldPos = new Vector3[m_lr.positionCount];
        for (int i = 0; i < m_oldPos.Length; ++i)
        {
            m_oldPos[i] = transform.position;
        }
        m_lr.SetPositions(m_oldPos);
        m_cnt = m_oldPos.Length - 1;
    }

    // Update is called once per frame
    void Update () {
        Vector3 wSpd = transform.rotation * Vector3.back * m_spd;
        m_cnt = Mathf.Max(0,m_cnt - 1);
        for (int i = m_oldPos.Length-1; i > m_cnt; --i)
        {
            m_oldPos[i] = m_oldPos[i-1]+wSpd*Time.deltaTime;
        }
        m_oldPos[m_cnt] = transform.position;
        m_lr.SetPositions(m_oldPos);
    }
}

実行するとオブジェクトの後ろ方向に軌跡が描画されます

2018-04-27_112440.png

マテリアルや見かけの移動速度などパラメータを調整します
m_spdは見かけのスピード、m_positionCountは軌跡の頂点数です

2018-04-27_112839.png

6
4
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
6
4