In this video I continue creating Tetris! This time I cover how to Move and Rotate Shapes, Except Keyboard Input, Spawn Shapes, Handle Custom Collisions, Debug, Make Shapes Fall, and Move Objects at Different Time Frames.
Like before I create all the code here blind with no previous preparation. All the code follows the video below.
If you like videos like this consider donating $1 on Patreon, or simply turn off AdBlock. Either helps a lot.
[googleplusone]
Code From the Video
Shape.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shape : MonoBehaviour { public float speed = 1.0f; float lastMoveDown = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKeyDown("a")) { transform.position += new Vector3(-1, 0, 0); Debug.Log(transform.position); if (!IsInGrid()) { transform.position += new Vector3(1, 0, 0); } } if (Input.GetKeyDown("d")) { transform.position += new Vector3(1, 0, 0); Debug.Log(transform.position); if (!IsInGrid()) { transform.position += new Vector3(-1, 0, 0); } } if (Input.GetKeyDown("s") || Time.time - lastMoveDown >= 1) { transform.position += new Vector3(0, -1, 0); Debug.Log(transform.position); if (!IsInGrid()) { transform.position += new Vector3(0, 1, 0); } lastMoveDown = Time.time; } if (Input.GetKeyDown("w")) { transform.Rotate(0, 0, 90); Debug.Log(transform.position); if (!IsInGrid()) { transform.Rotate(0, 0, -90); } } } public bool IsInGrid() { int childCount = 0; foreach(Transform childBlock in transform) { Vector2 vect = childBlock.position; childCount++; Debug.Log(childCount + " " + childBlock.position); if (!IsInBorder(vect)) { return false; } } return true; } public static bool IsInBorder(Vector2 pos) { return ((int)pos.x >= -4.73 && (int)pos.x <= 4.31 && (int)pos.y >= -10.45); } } |
ShapeSpawner.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShapeSpawner : MonoBehaviour { public GameObject[] shapes; public void SpawnShape() { int shapeIndex = Random.Range(0, 6); Instantiate(shapes[shapeIndex], transform.position, Quaternion.identity); } // Use this for initialization void Start () { SpawnShape(); } // Update is called once per frame void Update () { } } |
Leave a Reply