유니티/쯔꾸르
[유니티 강좌] 2D RPG 쯔꾸르 제작하기 Part 3 : 이동 불가 지역 설정하기(RayCast)
아메숑
2019. 3. 8. 15:31
출처 - https://www.youtube.com/watch?v=EdsVx9yN2Cc&list=PLUZ5gNInsv_NW8RQx8__0DxiuPZn3VDzP
1. 코드
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 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingObject : MonoBehaviour { private BoxCollider2D boxCollider; public LayerMask layerMask; //통과가 불가능한 레이어를 설정 public float speed; private Vector3 vector; public float runSpeed; private float applyRunSpeed; private bool applyRunFlag = false; public int walkCount; private int currentWalkCount; private bool canMove = true; private Animator animator; // Start is called before the first frame update void Start() { boxCollider = GetComponent<BoxCollider2D>(); animator = GetComponent<Animator>(); } IEnumerator MoveCoroutine() { while (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0) { if (Input.GetKey(KeyCode.LeftShift)) { applyRunSpeed = runSpeed; applyRunFlag = true; } else { applyRunSpeed = 0; applyRunFlag = false; } vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z); if (vector.x != 0) vector.y = 0; animator.SetFloat("DirX", vector.x); animator.SetFloat("DirY", vector.y); RaycastHit2D hit; //레이저를 쏴서 방해물이 있으면 방해물을 리턴하고, 아무것도 없으면 null리턴 Vector2 start = transform.position; //캐릭터의 현재위치 //speed = 2.4 walkCount = 20 이므로 48픽셀만큼 이동 Vector2 end = start + new Vector2(vector.x * speed * walkCount, vector.y * speed * walkCount); //캐릭터가 이동하고자 하는 곳 boxCollider.enabled = false; //캐릭터 자신의 박스컬라이더를 인식못하게 해줌 hit = Physics2D.Linecast(start, end, layerMask); boxCollider.enabled = true; if (hit.transform != null) //부딪히면 다음 명령어들은 실행하지 않음 break; animator.SetBool("Walking", true); while (currentWalkCount < walkCount) { if (vector.x != 0) { transform.Translate(vector.x * (speed + applyRunSpeed), 0, 0); } else if (vector.y != 0) { transform.Translate(0, vector.y * (speed + applyRunSpeed), 0); } if (applyRunFlag) currentWalkCount++; currentWalkCount++; yield return new WaitForSeconds(0.01f); } currentWalkCount = 0; } animator.SetBool("Walking", false); canMove = true; } // Update is called once per frame void Update() { if(canMove) { if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0) { canMove = false; StartCoroutine(MoveCoroutine()); } } } } | cs |
2. 과정
컴포넌트 Box Collider 2D 추가
Edit Collider를 누르고 충돌부분을 다리로 설정한다.
레이어 추가
빈 오브젝트를 생성하고, 컬라이더 박스 컴포넌트를 추가한 후 사이즈를 키운다. Layer는 Nopassing으로 해준다.
캐릭터의 Pivot을 다리쪽으로 내려주기 위해 0.5 0.2정도로 설정한다. apply를 해준다.
박스컬라이더를 다시 다리쪽으로 설정해준다.