ジャンプ、スライド、または回避
Coddyの「Unityゲーム:スカイレーン」コースのレッスン 11/21。
障害物が1種類なら、答えは1つです。ジャンプしましょう。3種類なら、3つの問いかけになります。
道にある赤い障壁、高さ y 0.5:ジャンプして乗り越えます。高さ y 1.95 に吊り下がった黄色いバー:その下を滑り抜けます。高さ y 1.5 で高さが3ユニットの紫色の壁:レーンを変更します。
バーと壁にも Obstacle タグが付いているので、すでに書いた衝突処理によって、それらにぶつかるとゲームが終了します。種類の番号をプレハブと高さに変換する小さなメソッドを2つ用意します。
GameObject Obstacle(int kind)
{
if (kind == 0) return barrierPrefab;
if (kind == 1) return barPrefab;
return wallPrefab;
}チャレンジ
簡単スライディングでくぐるバーと、避ける壁を追加します。
RoadにbarPrefabとwallPrefabを追加します。- 上記のように
Obstacle(kind)を書き、Height(kind)では、kindが0の場合は0.5f、kindが1の場合は1.95f、壁の場合は1.5fを指定します。 Fillでint kind = Random.Range(0, 3);を選び、Obstacle(kind)をHeight(kind)の位置に配置します。
「プレイ」を押すと、バリア、バー、壁が道路を流れてきます。そのどれに当たってもゲーム終了です。その後、「確認」を押します。
自分で試してみよう
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プレイグラウンド