Tanoda
CardStack2D.cs
Go to the documentation of this file.
1
5
6 using System.Collections;
7using System.Collections.Generic;
8using UnityEngine;
9using UnityEngine.UI;
10
12{
13
14public class CardStack2D : MonoBehaviour
15{
16
17 [SerializeField]
18 private float cardMoveSpeed = 8f;
19 [SerializeField]
20 private float buttonCooldownTime = 0.125f;
21 [SerializeField]
22 private int cardZMultiplier = 32;
23 [SerializeField]
24 private bool useDefaultUsedXPos = true;
25 [SerializeField]
26 private int usedCardXPos = 1280;
27 [SerializeField]
28 private Transform[] cards = null;
29
30 private int cardArrayOffset;
31 private Vector3[] cardPositions;
32 private int xPowerDifference;
33
36 public static bool canUseHorizontalAxis = true;
37
38 void Start()
39 {
42 xPowerDifference = 9 - cards.Length;
43
46 if (useDefaultUsedXPos)
47 {
48 int cardWidth = (int)(cards[0].GetComponent<RectTransform>().rect.width);
49 usedCardXPos = (int)(Screen.width * 0.5f + cardWidth);
50 }
51
52 cardPositions = new Vector3[cards.Length * 2 - 1];
53
55 for (int i = cards.Length; i > -1; i--)
56 {
57 if (i < cards.Length - 1)
58 {
59 cardPositions[i] = new Vector3(-Mathf.Pow(2, i + xPowerDifference) + cardPositions[i + 1].x, 0, cardZMultiplier * Mathf.Abs(i + 1 - cards.Length));
60 }
61 else
62 {
63 cardPositions[i] = Vector3.zero;
64 }
65 }
66
68 for (int i = cards.Length; i < cardPositions.Length; i++)
69 {
70 cardPositions[i] = new Vector3(usedCardXPos + 4 * (i - cards.Length), 0, -2 + -2 * (i - cards.Length));
71 }
72 }
73
74 void Update()
75 {
77 {
79 if (Input.GetAxisRaw("Horizontal") < 0 && cardArrayOffset > 0)
80 {
81 cardArrayOffset--;
82 StartCoroutine(ButtonCooldown());
83 }
84 else if (Input.GetAxisRaw("Horizontal") > 0 && cardArrayOffset < cards.Length - 1)
85 {
86 cardArrayOffset++;
87 StartCoroutine(ButtonCooldown());
88 }
89 }
90
92 for (int i = 0; i < cards.Length; i++)
93 {
94 cards[i].localPosition = Vector3.Lerp(cards[i].localPosition, cardPositions[i + cardArrayOffset], Time.deltaTime * cardMoveSpeed);
95 if (Mathf.Abs(cards[i].localPosition.x - cardPositions[i + cardArrayOffset].x) < 0.01f)
96 {
97 cards[i].localPosition = cardPositions[i + cardArrayOffset];
98
100 if (cards[i].localPosition.x == 0)
101 {
102 cards[i].gameObject.GetComponent<CanvasGroup>().interactable = true;
103 }
104 else
105 {
106 cards[i].gameObject.GetComponent<CanvasGroup>().interactable = false;
107 }
108 }
109 }
110 }
111
113 IEnumerator ButtonCooldown()
114 {
115 canUseHorizontalAxis = false;
116 yield return new WaitForSeconds(buttonCooldownTime);
118 }
119}
120}
Credit Erdener Gonenc - @PixelEnvision.