さらに混雑した列
Coddyの「Unityゲーム:スカイレーン」コースのレッスン 12/20。
1列に障害物が1つなら簡単です。ほかの2つのレーンは常に空いています。ゲームが進むにつれて、1列に2つか3つの障害物を配置しましょう。madeはすでにピースの数を数えているので、1列に配置できる障害物の数を設定できます。
int busy = Mathf.Min(3, 1 + made / 12);
int count = Random.Range(1, busy + 1);2つの障害物を同じレーンに置いてはいけません。空いているレーンをリストに入れ、使うたびにリストから1つ取り除きましょう。また、壁が3つ並ぶと通り抜けられなくなるので、壁が2つある場合は代わりにバリアかバーを選びます。
List<int> lanes = new List<int> { -1, 0, 1 };
int pick = Random.Range(0, lanes.Count);
int lane = lanes[pick];
lanes.RemoveAt(pick);チャレンジ
中級Fill内で、上記のようにbusyとcountを求めます。lanesから取り出したレーンそれぞれに、count個の障害物を配置します。- 壁の数を数えます。
kind == 2で、すでに2つある場合は、代わりにRandom.Range(0, 2)を選びます。
自分で試してみよう
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 GameManager game;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
game = FindFirstObjectByType<GameManager>();
}
void Update()
{
if (!game.over)
{
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;
}
void OnTriggerEnter(Collider other)
{
if (game.over) return;
if (other.CompareTag("Obstacle"))
{
game.GameOver();
}
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Unityゲーム:スカイレーンのすべてのレッスン
自分で練習してみよう: Unityプレイグラウンド