道を再利用する
Coddyの「Unityゲーム:スカイレーン」コースのレッスン 7/20。
7個のピースで道路は140ユニット分になります。1秒あたり10ユニットの速さでは、14秒でなくなります。必要になるたびに新しいピースを作り、古いピースを破棄する方法もありますが、もっと安価な方法があります。ランナーの後ろを通り過ぎたピースを前方に移動させ、再び使います。
ピースの中央が-chunkLengthを通り過ぎると、そのピースは完全に後方へ移動したことになります。7個のピースが並んでいるので、7個分の長さだけ前方に移動させると、最後のピースのすぐ後ろに配置できます。
if (chunk.position.z < -chunkLength)
{
chunk.position += Vector3.forward * chunkLength * chunks.Count;
}オブジェクトを破棄して新しく作る代わりに再利用する方法は、プーリングと呼ばれます。7個のピースで、終わりのない道路ができます。
チャレンジ
簡単Road.Update内で、区画が移動した後、完全に後方へ通り過ぎたら、上記のように前方へ移動させます。
自分で試してみよう
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public float laneSpeed = 16f;
public float jumpHeight = 1.6f;
public float gravity = -40f;
public float slideTime = 0.7f;
public int lane;
private CharacterController controller;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);
bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
StopSlide();
}
if ((Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) && controller.isGrounded)
{
slide = slideTime;
Resize(0.5f);
}
if (slide > 0f)
{
slide -= Time.deltaTime;
if (slide <= 0f) StopSlide();
}
if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;
float targetX = lane * laneWidth;
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
Vector3 move = new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f);
controller.Move(move);
}
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}
void Resize(float height)
{
controller.enabled = false;
transform.position += Vector3.up * (height - transform.localScale.y);
transform.localScale = new Vector3(1f, height, 1f);
controller.enabled = true;
}
}
Unityゲーム:スカイレーンのすべてのレッスン
自分で練習してみよう: Unityプレイグラウンド