Unity/3d/画面奥スクロール
提供: 初心者エンジニアの簡易メモ
サンプル
画面奥スクロールするように道が手前に流れる
参考:https://gomafrontier.com/unity/2514
少し改良してる
ScrollManager.cs
using UnityEngine; public class ScrollManager : MonoBehaviour { /// スクロール時の1ブロックとなるプレハブ [SerializeField] protected GameObject scrollBlockObject; /// ブロックの生成開始位置 [SerializeField] protected Transform blockPopPoint; /// ブロックの移動方向 protected Vector3 blockMoveForward; /// あらかじめブロックを生成しておく数 protected int before_block_create_count = 20; /// 最後の生成したブロックのRendererコンポーネント(処理用) private Renderer beforeBlockRenderer; void Start() { blockMoveForward = new Vector3(0, 0, -2f); if (0 < before_block_create_count) { Bounds blockRendererBounds = scrollBlockObject.GetComponent<Renderer>().bounds; blockRendererBounds.center = blockPopPoint.position; for (int i = 0; i < before_block_create_count; i++) { Vector3 createPosition = blockPopPoint.position + new Vector3( GetBinarizationFloat(blockMoveForward.x) * (blockRendererBounds.size.x * i), GetBinarizationFloat(blockMoveForward.y) * (blockRendererBounds.size.y * i), GetBinarizationFloat(blockMoveForward.z) * (blockRendererBounds.size.z * i) ); CreateBlock(createPosition); } } } private void FixedUpdate() { if (beforeBlockRenderer != null) { Bounds beforeBounds = beforeBlockRenderer.bounds; beforeBounds.size = beforeBlockRenderer.bounds.size * 2; beforeBounds.center += blockMoveForward; if (!beforeBounds.Contains(blockPopPoint.position)) { CreateBlock(blockPopPoint.position); } } } private void CreateBlock(Vector3 createPosition) { GameObject blockObject = Instantiate(scrollBlockObject, createPosition, scrollBlockObject.transform.rotation); blockObject.AddComponent<ScrollObject>().blockMoveForwardtranslate = blockMoveForward; blockObject.GetComponent<ScrollObject>().delTime = 5f; beforeBlockRenderer = blockObject.GetComponent<Renderer>(); } private float GetBinarizationFloat(float value) { if (0 < value) { return 1; } else if (value < 0) { return -1; } else { return 0; } } }
ScrollObject.cs
using UnityEngine; public class ScrollObject : MonoBehaviour { public float delTime; public Vector3 blockMoveForwardtranslate; void Start() { Destroy(gameObject, delTime); } void Update() { if (blockMoveForwardtranslate != Vector3.zero) { transform.Translate(blockMoveForwardtranslate, Space.World); } } }