쯔꾸르식 유니티 게임 공부

01.플레이어 케릭터 이동

ruripanda 2024. 12. 26. 16:36

본 강좌는 케이디님의 쯔꾸르풍 유니티 게임 만들기 강좌를 참고하여 만들었음을 알려드립니다

using System.Collections;
using UnityEngine;

public class MovingObjcet : MonoBehaviour
{
    //케릭터 이동속도
    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;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    //코루틴으로 이동제어 한칸 한칸 이동하게
    IEnumerator MoveCoroutine()
    {
        //시프트 키 입력 여부에 따라 뛰기 걷기 구분
        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);

        //캐릭터 이동구현 코드
        while (currentWalkCount < walkCount)
        {
            if (vector.x != 0)
            {
                //Translate는 현제 값에서 +를 해주는 코드
                transform.Translate(vector.x * (speed + applyRunSpeed), 0, 0);
            }
            else if (vector.y != 0)
            {
                transform.Translate(0, vector.y * (speed + applyRunSpeed), 0);
            }
            if(applyRunFlag)
                currentWalkCount++;//위의 applyRunFlas가 되면 추가되는 카운트 만약 아니라면 더해지지 않음
            currentWalkCount++;//위의 카운트와는 별개의 카운트로 구분 됨
            yield return new WaitForSeconds(0.01f);//0.01초마다 대기
        }
        currentWalkCount = 0;//0을 넣어서 반복문 초기화
       
        //한칸한칸 이동할때 bool값
        canMove = true;
    }

    //매 프레임마다 이동명령을 받음
    void Update()
    {
        if (canMove)
        {
            //이동 방향키 입력을 할때 쯔구르 처럼 상하좌우 구분하게 하는 코드
            if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0)
            {
                //한칸 한칸 이동할때 bool값으로 canMove를 이용함
                canMove = false;
                StartCoroutine(MoveCoroutine());
            }
        }
    }
}

 

검색어 유입

이동, 시프트 달리기, 달리기, 픽셀만큼 걷기. 2D걷기, 백터3, 코루틴 이동