summaryrefslogtreecommitdiff
path: root/SurvivalTest/Assets/Scripts/Test/TestBrokenPiece.cs
blob: 4399886e7b252028413be3705df21aaad05e684c (plain)
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
98
99
100
101
102
103
104
105
106
107
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestBrokenPiece : MonoBehaviour
{
	[SerializeField] private List<Sprite> m_Pieces;

	private TestFakeHeight m_Coord;

	private Vector3 m_Velocity;

	private Vector3 m_Gravity = new Vector3(0, 0, -9.8f);

	private float m_Damp = 0.5f;

	private SpriteRenderer m_SpriteRenderer;

	enum State
	{
		Avlie ,
		Dead ,
	}

	State m_State;

	private void Awake()
	{
		m_Coord = GetComponent<TestFakeHeight>();
		m_SpriteRenderer = GetComponent<SpriteRenderer>();
	}

	public void Set(Vector3 position, Vector3 dir, float speed, int index)
	{
		m_Coord = GetComponent<TestFakeHeight>();
		m_SpriteRenderer = GetComponent<SpriteRenderer>();

		m_Coord.x = position.x;
		m_Coord.y = position.y;
		m_Coord.height = position.z;

		m_Velocity = dir * speed;

		m_SpriteRenderer.sprite = m_Pieces[index % m_Pieces.Count];

		m_State = State.Avlie;
	}

	private void Update()
	{
		if(m_State == State.Avlie)
		{
			m_Velocity += m_Gravity * Time.deltaTime;

			m_Coord.x += m_Velocity.x * Time.deltaTime;
			m_Coord.y += m_Velocity.y * Time.deltaTime;
			m_Coord.height += m_Velocity.z * Time.deltaTime;

			if (m_Coord.height < 0)
			{
				m_Coord.height = 0;

				// bounce 
				m_Velocity.x = m_Velocity.x * m_Damp;
				m_Velocity.y = m_Velocity.y * m_Damp;
				m_Velocity.z = -m_Velocity.z * m_Damp;

				if (m_Velocity.magnitude < 0.1f)
				{
					m_State = State.Dead;
					StartCoroutine(coDead(Random.Range(1f, 3f)));
				}
			}
		}
		else if(m_State == State.Dead)
		{
		}
	}

	IEnumerator coDead( float time)
	{
		Color c = m_SpriteRenderer.color;

		float t = 0;
		while (true)
		{
			t += Time.deltaTime;

			c.a = (time - t) / time;

			m_SpriteRenderer.color = c;

			if(t > time)
			{
				break;
			}

			yield return null;
		}

		this.gameObject.SetActive(false);
		Destroy(this.gameObject);

		yield break;
	}

}