유니티/쯔꾸르
[유니티 강좌] 2D RPG 쯔꾸르 제작하기 Part 2
아메숑
2019. 3. 8. 14:40
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 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingObject : MonoBehaviour { //public은 유니티 엔진에서 나타난다. public float speed; //걷는 속도 private Vector3 vector; public float runSpeed; //뛰는속도 private float applyRunSpeed; //엔진에서 입력한 뛰는 속도를 받아서 여기에 대입 private bool applyRunFlag = false; //True이면 뛴다.(쉬프트 누르면 뜀) public int walkCount; //방향기를 계속 누르고 있을 때, 계속 걸음이 처음부터 시작되지 않도록 private int currentWalkCount; //걸음수를 카운트해서 walkCount보다 작을때는 걸음을 다시 시작할 수 없도록한다. private bool canMove = true; //currentWalkCount<walkCount 일 때는 false private Animator animator; // Start is called before the first frame update void Start() { 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; } //Horizontal은 우=1,좌=-1.만약 왼쪽 방향키를 누르면 (-1,0,0) 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); 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 |