コイン
Coddyの「Unityゲーム:スカイレーン」コースのレッスン 13/20。
コインは、道を塞ぐものがないときにプレイヤーがレーンを変える理由になります。各ピースには、障害物の後ろに、ピースに沿って4、7、10、13の位置、yが1の高さで、1つのレーンに4枚並びます。
コインは専用のスクリプトで自動的に回転します。
void Update()
{
transform.Rotate(0f, 0f, spinSpeed * Time.deltaTime);
}コインのプレハブは横向きに配置されているため、コイン自身のz軸が上を向いています。そのため、z軸を中心に回すと、テーブルの上のコインのように回転します。
コインを集めるのはRunnerの役目です。同じOnTriggerEnterで、コインがgame.AddCoin()を通じて1枚追加され、破棄されます。
チャレンジ
簡単Coinにpublic float spinSpeed = 180f;と上記のUpdateを追加します。RoadにcoinPrefabを追加し、Fillの最後でランダムなレーンのz位置4f + i * 3fにコインを4枚配置します。GameManagerにpublic TMP_Text coinText;、public int coins;、public void AddCoin()(コインを1枚追加してから、ShowScore()を呼び出す)を追加します。ShowScoreでは、coinText.text = "Coins: " + coins;も設定します。Runner.OnTriggerEnterにelse if (other.CompareTag("Coin"))を追加し、コインを加算して破棄します。
自分で試してみよう
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プレイグラウンド