본문 바로가기
프로그래밍

Line Drawing 전체 스크립트

by HyunS_PG 2020. 5. 13.
반응형

 

DrawLine.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class DrawLine : MonoBehaviour
{
    public GameObject linePrefab;           //선 형태 프리펩
    public GameObject ballPrefab;           //공 형태 프리펩
    public GameObject currentLine;          //선 오브젝트
    public LineRenderer lineRenderer;       //브러쉬같은 역할을 하는 라인 렌더러
    public EdgeCollider2D edgeCollider;     //선에 사용되는 엣지 콜라이더
    public List<Vector2> fingerPositions;   //선의 정점들 위치를 저장하기 위한 리스트
    //public GameObject pencilPrefab;       //연필 브러쉬 프리펩(테스트)
    //public GameObject pencilLine;         //연필 브러쉬 오브젝트(테스트)
 
    Vector3 line_StartPos;                  //선의 처음 위치(공을 만들기 위한 용도)
    Vector3 line_EndPos;                    //선의 마지막 위치(공을 만들기 위한 용도)
    bool isRedBall;                         //선을 만들 것인지 공을 만들 것인지 체크
    [HideInInspector]public bool isDrawing;                         //그리고 있는 중인지 체크(플레이어가 그림을 그릴 때 움직이지 못하기 위한 용도)
 
    public GameObject player;       //플레이어
 
    public Slider pencilSlider;     //연필심 양을 보여주는 UI
    public float maxPencil = 100f;  //연필심 최대 양
    public GameObject emptyText;    //연필심이 다 떨여졌을 때 알림 메세지
    [HideInInspector] public bool isEmpty;                   //연필심이 다 떨어졌는지 체크
 
    AudioSource audio;
 
    private void Start()
    {
        pencilSlider.maxValue = maxPencil;
 
        isRedBall = false;
        isDrawing = false;
        isEmpty = false;
 
        audio = GetComponent<AudioSource>();
        audio.loop = true;
    }
 
    void Update()
    {
        //빨간 공인지 체크
        RedBallChk();
 
        //플레이어가 죽은 상태인지 확인
        if (!FindObjectOfType<PlayerController>().isDead)
        {
            //마우스 왼쪽 버튼을 눌렀을 때 && 연필심 양이 남았을 때
            if (Input.GetMouseButtonDown(0&& !isEmpty)
            {
                audio.Play();           //선 그리는 소리
 
                isDrawing = true;       //그리는 중
                
                if (!isRedBall)         //빨간 공이 아니면
                {
                    PencilQuantity(-3); //연필심 양 -3
                    CreateLine();       //선 오브젝트 생성
                }
                else
                {
                    FindObjectOfType<RedBall>().ScaleUp(layerChk("Ball").collider.transform);   //공 크기 커지게 하는 함수
                }
 
                player.GetComponent<Animator>().SetBool("Drawing"true);   //플레이어 그리기 애니메이션
            }
 
            //마우스 왼쪽 버튼을 누르고 있을 때 && 빨간 공이 아닐 때 && 연필심 양이 남았을 때
            else if (Input.GetMouseButton(0&& !isRedBall && !isEmpty)
            {
 
                Vector2 tempFingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);    //커서 위치
 
                //점과 점 거리가 0.1f이상될 때 이어서 선 생성
                if (Vector2.Distance(tempFingerPos, fingerPositions[fingerPositions.Count - 1]) > .1f)
                {
                    PencilQuantity(-1);
                    UpdateLine(tempFingerPos);
                }
 
                //선 끝지점
                line_EndPos = fingerPositions[fingerPositions.Count - 1];
            }
 
            //마우스 왼쪽 버튼을 땔 때 && 빨간 공이 아닐 때 && 연필심 양이 남았을 때
            else if (Input.GetMouseButtonUp(0&& !isRedBall && !isEmpty)
            {
                audio.Stop();
 
                //선 첫 지점과 끝 지점 위치가 같을 때 점에 중력이 작용
                if (Vector2.Distance(line_EndPos, line_StartPos) < 0.1f && lineRenderer.positionCount < 3)
                {
                    PencilQuantity(-3); //연필심 양 -3
 
                    currentLine.GetComponent<Rigidbody2D>().isKinematic = false;
                    currentLine.GetComponent<EdgeCollider2D>().edgeRadius = 0.08f;
 
                    FindObjectOfType<RendererToCollider>().EdgePosCreate();
 
                    #region 빨간색 버튼
                    //빨간색 공 생성
                    GameObject go = Instantiate(ballPrefab, line_EndPos, Quaternion.identity);
 
                    //선을 빨간색 버튼의 부모로 설정
                    go.transform.SetParent(currentLine.transform);
                    #endregion
                }
                isDrawing = false;
 
                player.GetComponent<Animator>().SetBool("Drawing"false);
            }
 
            //마우스 왼쪽 버튼을 땔 때 && 빨간 공일 때
            else if (Input.GetMouseButtonUp(0&& isRedBall && !isEmpty)
            {
                audio.Stop();
 
                isDrawing = false;
 
                player.GetComponent<Animator>().SetBool("Drawing"false);
            }
 
            //마우스 오른쪽 버튼을 눌렀을 때
            else if (Input.GetMouseButtonDown(1))
            {
 
                if(!isRedBall)
                    EraseLIne("Line");
                else
                    EraseLIne("Ball");
            }
        }
 
    }
 
    //선 생성 함수
    void CreateLine()
    {
        //선 생성 준비
        currentLine = Instantiate(linePrefab, Vector3.zero, Quaternion.identity);
        lineRenderer = currentLine.GetComponent<LineRenderer>();
        edgeCollider = currentLine.GetComponent<EdgeCollider2D>();
        fingerPositions.Clear();
 
        //선 생성
        line_StartPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        fingerPositions.Add(line_StartPos);
        fingerPositions.Add(line_StartPos);
        lineRenderer.SetPosition(0, fingerPositions[0]);
        lineRenderer.SetPosition(1, fingerPositions[1]);
        edgeCollider.points = fingerPositions.ToArray();
    }
 
    //선 그리기 함수
    void UpdateLine(Vector2 newFingerPos)
    {
        fingerPositions.Add(newFingerPos);
        lineRenderer.positionCount++;
        lineRenderer.SetPosition(lineRenderer.positionCount - 1, newFingerPos);
        edgeCollider.points = fingerPositions.ToArray();
 
        #region 연필 브러쉬
        //pencilLine = Instantiate(pencilPrefab, newFingerPos, Quaternion.identity);
        //pencilLine.transform.Rotate(0, 0, Random.Range(0, 180f));
        //pencilLine.transform.SetParent(currentLine.transform);
        #endregion
    }
 
    //선 지우기 함수
    void EraseLIne(string layerName)
    {
        RaycastHit2D hit = layerChk(layerName);
 
        if (hit.collider != null)
        {
            GameObject target = hit.collider.gameObject;
 
            if (!isRedBall)
                Destroy(target);
            else
                Destroy(target.transform.parent.gameObject);
        }
    }
 
    //커서가 빨간공 위에 있는지 체크하는 함수
    void RedBallChk()
    {
        RaycastHit2D hit = layerChk("Ball");
 
        if (hit.collider != null)
            isRedBall = true;
        else
            isRedBall = false;
    }
 
    //특정 레이어의 RaycastHit2D를 반환하는 함수
    RaycastHit2D layerChk(string layerName)
    {
        Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
 
        int layerMask = 1 << LayerMask.NameToLayer(layerName);
        RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero, 0f, layerMask);
 
        return hit;
    }
 
    //연필심 양 조절하는 함수
    public void PencilQuantity(int x)
    {
        pencilSlider.value += x;
 
        if(pencilSlider.value <= 1)
        {
            audio.Stop();
 
            emptyText.SetActive(true);
            isEmpty = true;
            isDrawing = false;
 
            player.GetComponent<Animator>().SetBool("Drawing"false);
        }
    }
}
 
cs

 

 

RedBall.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class RedBall : MonoBehaviour
{
    //공 크기 커지게 하는 함수
    public void ScaleUp(Transform hitCollider)
    {
        if (hitCollider.localScale.x < 3.5)     //공 최대 크기 3.5
        {
            hitCollider.localScale = new Vector2(hitCollider.localScale.x * 1.5f, hitCollider.localScale.y * 1.5f);
            transform.parent.GetComponent<Rigidbody2D>().mass *= 1.6f;
        }
    }
 
    private void OnTriggerEnter2D(Collider2D collision)
    {
        //공이 땅 밑으로 떨어지면 2초 후 삭제
        if (collision.tag == "DeadZone")
            Destroy(gameObject, 2f);
    }
}
 
cs

 

 

GameManager.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
 
public class GameManager : MonoBehaviour
{
    public GameObject gameoverText;     //게임오버 텍스트
    public GameObject gameclearText;    //게임클리어 텍스트
 
    void Update()
    {
        //리셋버튼
        if (Input.GetKey(KeyCode.R))
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    }
 
    //다음 씬으로 넘어가기 함수
    public void NextScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }
 
    //클리어시
    public void ClearScene()
    {
        gameclearText.SetActive(true);
    }
 
    //게임 오버시
    public void Gameover()
    {
        gameoverText.SetActive(true);
    }
}
 
cs

 

 

PlayerController.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
98
99
100
101
102
103
104
105
106
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PlayerController : MonoBehaviour
{
    [HideInInspector] public Rigidbody2D rb2D;       //플레이어 Rigidbody
    [HideInInspector] public Animator animator;      //플레이어 애니메이터
    [HideInInspector] public GameObject playerFoot;  //플레이어 발
 
    float walk_Speed = 170f;    //플레이어 걷기 속도
    [HideInInspector] public bool isGrounded;            //땅 위에 있는지 체크
 
    float jump_Force = 260f;    //플레이어 점프력
    [HideInInspector] public int jumpCount = 1;          //플레이어 연속 점프 가능한 횟수
 
    [HideInInspector] public bool isDead;    //플레이어가 죽은 상태인지 체크
 
    void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
 
        isGrounded = false;
        isDead = false;
    }
    
    void Update()
    {
        playerMove();   //플레이어 움직임 연산
    }
 
    //플레이어 이동
    void playerMove()
    {
        //플레이어가 죽은 상태가 아니고 그리는 중이 아닐 때 움직일 수 있다는 조건
        if (!isDead && !FindObjectOfType<DrawLine>().isDrawing)
        {
            //횡이동
            int horizontal = (int)Input.GetAxisRaw("Horizontal");
 
            //이동할 때
            if (horizontal != 0)
            {
                transform.localScale = new Vector3(horizontal, 11);
 
                rb2D.velocity = new Vector2(walk_Speed * horizontal * Time.deltaTime, rb2D.velocity.y);
 
                //땅위에 있으면
                if (isGrounded)
                    animator.SetBool("Walk"true);
            }
            //움직이지 않을 때
            else
            {
                rb2D.velocity = new Vector2(0, rb2D.velocity.y);
                animator.SetBool("Walk"false);
            }
 
            //점프할 때
            if (Input.GetKeyDown(KeyCode.Space) && jumpCount < 1 && isGrounded)
            {
                isGrounded = false;
                jumpCount++;
 
                rb2D.velocity = new Vector2(00);
                rb2D.AddForce(transform.up * jump_Force);
 
                animator.SetBool("Jump"true);
            }
        }
    }
 
    //특정 오브젝트와 트리거됐을 때
    private void OnTriggerEnter2D(Collider2D collision)
    {
        //연필심 아이템
        if (collision.tag == "Resource")
        {
            FindObjectOfType<DrawLine>().pencilSlider.value = FindObjectOfType<DrawLine>().maxPencil;   //연필심 양 최대로
            FindObjectOfType<DrawLine>().emptyText.SetActive(false);    //Empty텍스트 비활성화
            FindObjectOfType<DrawLine>().isEmpty = false;               //연필심 없는 상태 비활성화
 
            Destroy(collision.gameObject);  //연필심 아이템은 맵에서 삭제
        }
    }
 
    private void OnCollisionEnter2D(Collision2D collision)
    {
        //플레이어가 닿으면 죽는 지역
        if (collision.collider.tag == "DeadZone")
        {
            Die();
        }
    }
 
    //죽었을 때
    public void Die()
    {
        isDead = true;
        FindObjectOfType<GameManager>().Gameover();
 
        animator.SetTrigger("Dead");
    }
}
 
cs

 

 

GroundCheck.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class GroundCheck : MonoBehaviour
{
    public GameObject player;
 
    private void OnCollisionEnter2D(Collision2D collision)
    {
        //땅이나 선에 닿을시
        if (collision.transform.tag == "Line" || collision.transform.tag == "Ground")
        {
            player.GetComponent<PlayerController>().animator.SetBool("Jump"false);
        }
    }
 
    private void OnCollisionStay2D(Collision2D collision)
    {
        //땅이나 선에 서있을 때
        if (collision.transform.tag == "Line" || collision.transform.tag == "Ground")
        {
            player.GetComponent<PlayerController>().jumpCount = 0;      //점프한 횟수 초기화
            player.GetComponent<PlayerController>().isGrounded = true;  //땅위에 있는 상태 true
        }
    }
    private void OnCollisionExit2D(Collision2D collision)
    {
        //땅이나 선에서 떨어졌을 때
        if (collision.transform.tag == "Line" || collision.transform.tag == "Ground")
        {
            player.GetComponent<PlayerController>().isGrounded = false//땅위에 있는 상태 false
        }
    }
}
 
cs

 

BackgroundScroll.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BackgroundScroll : MonoBehaviour
{
    Transform camera_Tran;
    Transform player;
    float width;
 
    void Awake()
    {
        BoxCollider2D backgoundCollider = GetComponent<BoxCollider2D>();
        width = backgoundCollider.size.x;
    }
 
    void Start()
    {
        player = GameObject.Find("Player").transform;
        camera_Tran = GameObject.Find("Main Camera").transform;
    }
    
    void Update()
    {
        #region 배경이 원근감 있게 움직이게 하는 연산
        //int bg_dir = 0;
 
        //if (player.GetComponent<Rigidbody2D>().velocity.x > 1f && Camera.main.transform.position.x >= 0f)
        //    bg_dir = 1;
        //else if (player.GetComponent<Rigidbody2D>().velocity.x < -1f && Camera.main.transform.position.x >= 0f)
        //    bg_dir = -1;
 
        //transform.Translate(player.right * bg_dir * Time.deltaTime);
        #endregion
 
        transform.position = new Vector2(transform.position.x, camera_Tran.position.y);
        
        //배경이 움직이는 방향
        if (camera_Tran.position.x - transform.position.x >= width)
            Reposition(1);
        else if (transform.position.x - camera_Tran.position.x > width)
            Reposition(-1);
    }
 
    //배경 이동 함수
    void Reposition(int dir)
    {
        Vector2 offset = new Vector2(width * 2f * dir, 0);
        transform.position += (Vector3)offset;
    }
}
 
cs

 

 

CameraMove.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CameraMove : MonoBehaviour
{
    Transform player;
    void Start()
    {
        player = GameObject.Find("Player").transform;    
    }
    void Update()
    {
        transform.position = new Vector3(player.position.x, player.position.y, -10);
 
        //카메라 이동 x축 제한
        if(transform.position.x < 0f)
        {
            transform.position = new Vector3(0, transform.position.y, -10);
        }
 
        //카메라 이동 y축 제한
        if (transform.position.y < 0f)
        {
            transform.position = new Vector3(transform.position.x, 0f, -10);
        }
        else if (transform.position.y > 3f)
        {
            transform.position = new Vector3(transform.position.x, 3f, -10);
        }
    }
}
 
cs

 

 

BulletSpawner.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BulletSpawner : MonoBehaviour
{
    public GameObject bulletPrefab;
 
    float delta = 0;
    public float spawnTime = 3f;
    
    void Update()
    {
        delta += Time.deltaTime;
 
        //발사 시간 간격
        if(delta > spawnTime)
        {
            delta = 0f;
 
            Vector3 x = new Vector3(1.75f, 00);
 
            //총알 생성
            GameObject bullet = Instantiate(bulletPrefab, transform.position + (x * transform.localScale.x), transform.rotation);
            bullet.transform.SetParent(transform);
        }
    }
 
    private void OnTriggerEnter2D(Collider2D collision)
    {
        //적이 땅 밑으로 떨어지면 2초 후 삭제
        if(collision.tag == "DeadZone")
            Destroy(gameObject, 2f);
    }
}
 
cs

 

 

CannonBullet.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CannonBullet : MonoBehaviour
{
    public float speed;
 
    Rigidbody2D rb2D;
    
    void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
 
        //적이 바라보고 있는 방향으로 등속도 발사
        transform.localScale = new Vector3(-transform.localScale.x * transform.parent.localScale.x, 11);
        rb2D.velocity = transform.parent.localScale.x * transform.right * speed;
    }
 
    private void OnCollisionEnter2D(Collision2D collision)
    {
        //선이나 공에 닿을 때
        if(collision.collider.tag == "Line" || collision.collider.tag == "Ball")
        {
            Destroy(collision.gameObject);  //선이나 공 삭제
            Destroy(gameObject);            //자기 자신 삭제
        }
        //오브젝트, 땅, 플레이어와 닿을 때
        else if(collision.collider.tag == "Object" || collision.collider.tag == "Ground" || collision.collider.tag == "Player")
        {
            Destroy(gameObject);    //자기 자신 삭제
        }
    }
}
 
cs

 

 

PortalFunction.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;
using UnityEngine.SceneManagement;
 
public class PortalFunction : MonoBehaviour
{
    float rotateSpeed = 10f;
 
    void Update()
    {
        transform.Rotate(00, rotateSpeed);
    }
 
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "Player")
        {
            //엔딩 스테이지가 2일 때
            if(SceneManager.GetActiveScene().buildIndex == 2)
                FindObjectOfType<GameManager>().ClearScene();
            else 
                FindObjectOfType<GameManager>().NextScene();
        }
    }
}
 
cs
반응형

'프로그래밍' 카테고리의 다른 글

Zombie Survive 전체 스크립트  (0) 2020.06.01
Line Drawing 스크립트 설명  (0) 2020.05.13
DigDog 스크립트 설명  (0) 2020.05.08
DigDog 전체 스크립트  (0) 2020.05.07
[유니티 연습] 20160123 2D 키보드 조작+회전  (0) 2016.02.02