Menu
CoddyTech

生き残ってスコアを稼ごう

CoddyのUnityジャーニー「Unityスクリプティングの基礎」セクションの一部。レッスン 64/67。

challenge icon

チャレンジ

中級

最後のステップ:スコアと、難易度が上がっていくゲーム。これまでのステップの内容はすべてそのままにして、次を追加します:

  • 生き残った秒数を数える、scoreという名前のfloat:ゲームの実行中、毎フレーム、そのフレームの経過時間を加算します。
  • Inspectorで設定するspeedUpフィールド(0.2)。fallSpeedは毎秒speedUpずつ増加します。毎フレーム少しずつ増えるため、ブロックはどんどん速く落下します。
  • 衝突したときは、Game overではなくGame over! Score: 12をログに出力します。scoreの秒数の整数部分を使います(intにキャストします)。

Playを押してハイスコアを目指し、それからCheckを押します。

自分で試してみよう

using System.Collections.Generic;
using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private float spawnEvery = 1f;
    [SerializeField] private float fallSpeed = 5f;

    private List<GameObject> blocks = new List<GameObject>();
    private float timer;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;

        timer += Time.deltaTime;
        if (timer >= spawnEvery)
        {
            timer = 0f;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }

        for (int i = blocks.Count - 1; i >= 0; i--)
        {
            blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
            Vector3 b = blocks[i].transform.position;
            if (Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f)
            {
                Debug.Log("Game over");
                enabled = false;
                return;
            }
            if (b.y < -1f)
            {
                Destroy(blocks[i]);
                blocks.RemoveAt(i);
            }
        }
    }
}

Unityスクリプティングの基礎のすべてのレッスン