SlidingHidder.cs
1.56 KB
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
using UnityEngine;
using System.Collections;
public class SlidingHidder : MonoBehaviour {
public bool visible = true;
public bool slideOnX = true;
public bool toLeft = true;
public bool slideOnY = false;
public bool toTop = false;
public float speed = 1f;
public bool disableWhenHidden = true;
private Transform transform;
private Vector2 hiddenPosition;
private Vector2 visiblePosition;
public void setVisible(bool visible)
{
this.gameObject.SetActive(true);
this.visible = visible;
}
void Start ()
{
transform = this.gameObject.transform;
Rect obj = this.gameObject.GetComponent<RectTransform>().rect;
visiblePosition = transform.position;
hiddenPosition = visiblePosition;
if (slideOnX) hiddenPosition.x += toLeft ? -obj.width : obj.width;
if (slideOnY) hiddenPosition.y += toTop ? -obj.height: obj.height;
transform.position = visible ? visiblePosition : hiddenPosition;
this.gameObject.SetActive(visible);
}
void Update ()
{
Vector2 position = transform.position;
Vector2 objective = visible ? visiblePosition : hiddenPosition;
if (slideOnX && Mathf.Abs(position.x - objective.x) > speed)
position.x += position.x < objective.x ? speed : -speed;
else
position.x = objective.x;
if (slideOnY && Mathf.Abs(position.y - objective.y) > speed)
position.y = position.y + (position.y < objective.y ? speed : -speed);
else
position.y = objective.y;
transform.position = position;
this.gameObject.SetActive(!disableWhenHidden
|| (position.x != hiddenPosition.x || position.y != hiddenPosition.y)
);
}
}