61.#4

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlockController : MonoBehaviour
{
    // 落下タイマー
    float fallTimerMax = 0.5f;
    float fallTimer;

    // シーンディレクター
    [SerializeField] TetrisPuzzleSceneDirector gameSceneDirector;

    // Start is called before the first frame update
    void Start()
    {
        fallTimer = fallTimerMax;
    }

    // Update is called once per frame
    void Update()
    {
        // 落下タイマー消化
        fallTimer -= Time.deltaTime;

        // 移動する方向
        Vector3 movePosition = Vector3.zero;

        // 左移動
        if(Input.GetKeyUp(KeyCode.LeftArrow))
        {
            movePosition = Vector3.left;
        }
        // 右移動
        else if (Input.GetKeyUp(KeyCode.RightArrow))
        {
            movePosition = Vector3.right;
        }
        // 下移動
        else if (Input.GetKeyUp(KeyCode.DownArrow))
        {
            movePosition = Vector3.down;
        }
        // 回転
        else if (Input.GetKeyUp(KeyCode.UpArrow))
        {
            transform.Rotate(new Vector3(0, 0, 1), 90);
            if(!gameSceneDirector.IsMovable(transform))
            {
                transform.Rotate(new Vector3(0, 0, 1), -90);
            }
        }

        // 時間経過で下移動
        if(fallTimer < 0)
        {
            movePosition = Vector3.down;
            fallTimer = fallTimerMax;
        }

        // 移動
        transform.position += movePosition;

        // 移動できなかった場合
        if(!gameSceneDirector.IsMovable(transform))
        {
            // 元に戻す
            transform.position -= movePosition;

            // 下に移動できなかった場合は終了
            if(movePosition == Vector3.down)
            {
                enabled = false;
            }
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TetrisPuzzleSceneDirector : MonoBehaviour
{
    // フィールドサイズ
    const int FieldWidth = 10;
    const int FieldHeight = 20;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    // ワールド座標をインデックス座標に変換
    Vector2Int GetIndexPosition(Vector3 position)
    {
        Vector2Int index = new Vector2Int();

        index.x = Mathf.RoundToInt(position.x - 0.5f) + FieldWidth / 2;
        index.y = Mathf.RoundToInt(position.y - 0.5f) + FieldHeight / 2;

        return index;
    }

    // 移動可能か
    public bool IsMovable(Transform blockTransform)
    {
        foreach (Transform item in blockTransform)
        {
            Vector2Int index = GetIndexPosition(item.position);

            // 左右と下
            if(index.x < 0 || FieldWidth-1 < index.x || index.y < 0)
            {
                return false;
            }
        }

        return true;
    }
}
テトリス

前の記事

60.#3
テトリス

次の記事

62.#5