障害物
Coddyの「Unityゲーム:スカイレーン」コースのレッスン 9/20。
道路には、よけるものが必要です。各ピースの中央に、ランダムなレーンで障害物を配置します。これを行うのがFillメソッドです。Startで新しいピースごとに呼び出し、ピースが先頭に戻るたびにも呼び出します。
プレイヤーに少し時間を与えるため、最初の2つのピースは空のままにします。Roadは、madeで埋めたピースの数を数えます。
void Fill(Transform chunk)
{
made++;
if (made <= safeChunks) return;
int lane = Random.Range(-1, 2);
Place(chunk, barrierPrefab, lane, 0.5f, 0f);
}Random.Range(-1, 2)は-1、0、または1です。整数の場合、2つ目の数値が選ばれることはありません。
再利用されるピースには、以前の障害物が残っています。Clearは、タグが付いた子オブジェクトをすべて破棄します。床、ダッシュ、端にはタグが付いていないため、そのまま残ります。
void Clear(Transform chunk)
{
foreach (Transform child in chunk)
{
if (!child.CompareTag("Untagged")) Destroy(child.gameObject);
}
}チャレンジ
簡単Roadにpublic GameObject barrierPrefab;、public int safeChunks = 2;、private int made;を追加します。Place(chunk, prefab, lane, y, z)を記述します。これはchunk.position + new Vector3(lane * laneWidth, y, z)の位置に、prefab.transform.rotationを使って、ピースの子としてプレハブを生成します。- 上記のように
FillとClearを記述します。 - Startで各ピースに対して
Fill(chunk)を呼び出し、ピースが前方に移動したときにClear(chunk); Fill(chunk);を呼び出します。
自分で試してみよう
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プレイグラウンド