道を動かす
Coddyの「Unityゲーム:スカイレーン」コースのレッスン 6/20。
ランナーゲームでは、プレイヤーはその場にとどまり、世界のほうが向かってきます。カメラとプレイヤーをずっと前進させても動作しますが、数値が際限なく大きくなります。道路を動かせば、すべてをゼロの近くに保てます。
速度はゲーム全体に関わるため、GameManagerに保持します。RoadはStartで一度それを取得し、毎フレーム速度を読み取ります。
float step = game.speed * Time.deltaTime;
foreach (Transform chunk in chunks)
{
chunk.position += Vector3.back * step;
}Vector3.backは(0, 0, -1)、つまりカメラの方向です。あとでピースを動かせるように、RoadはそれらをList<Transform>に記録しておく必要があります。
チャレンジ
簡単GameManagerにpublic float startSpeed = 10f;とpublic float speed;を追加し、Startでspeed = startSpeedを設定します。Roadにprivate List<Transform> chunks = new List<Transform>();(using System.Collections.Generic;を含める)とprivate GameManager game;を追加します。- Startで
game = FindFirstObjectByType<GameManager>();を設定し、新しいピースをすべてchunksに追加します。 - 上記のように
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プレイグラウンド