솔룩스/유니티스터디

유니티강좌-1

조강학 2025. 4. 6. 03:23

먼저 2d 환경의 새 프로젝트를 생성해준다. 

 

다운받은 리소스를 asset 폴더에 풀어준다. 

 

먼저 캐릭터 이동에 대해 배워본다. 

 


 

캐릭터 이동

 

다운받은 이미지가 하나의 덩어리로 뭉쳐있다. 이를 쪼개기 위해 유니티의 기능을 사용한다. 

스프라이트 모드를 싱글 -> 멀티플로 변경한다. 

 

다운받은 캐릭터 이미지가 가로 3 * 세로 4 이므로 이를 기준으로 4행 3열로 잘라주면 된다. 

 

자른 후 apply로 적용한다. 

 

이후 분할 된 이미지를 사용하면 된다 . 기본 48 픽셀 기준으로 바꿔준다. 

 

픽셀 위주 게임의 경우 포인터를 사용한다. 

 

--> 현재 유니티에서 스프라이트를 자동으로 분할해주는 듯?

 

 

이미지를 화면에 끌어오고 에셋 폴더에 캐릭터 이동을 담당할 스크립트를 하나 작성한다. 

( assets 안에 스크립트 폴더를 생성한다. )

 

 

 

Input.GetAxisRaw("Horizontal")  

우 방향키는 1, 좌 방향키는 -1 return 

 

Input.GetAxisRaw("Vertical")  

상 방향키 1, 하 방향키 -1 return ;

 

translate 함수는 현재 값에서 매개변수 값 만큼 추가로 이동

 

 

using UnityEngine;

public class MovingBehavi : MonoBehaviour
{
    public float speed;
    public Vector3 vector;
    

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()//매 프레임 실행
    {

        if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") == 0) {
            vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z);
        }
        if(vector.x != 0)
        {
            transform.Translate(vector.x * speed, 0, 0);
        }
        else if (vector.y != 0)
        {
            transform.Translate(0, vector.y * speed, 0);
        }
    }
}

 

 

캐릭터에 이 스크립트를 부착하고 play하면 캐릭터의 이동을 볼 수 있다. (speed 값 주는거 잊지 말기)

 

속도를 1로 주었는데 너무 빨라 --> 캐릭터의 크기를 키워 속도를 조절한다. 

 

추가로 shift키 눌렀을 때 빨라지는 것도 구현한다. 

using UnityEngine;

public class MovingBehavi : MonoBehaviour
{
    public float speed;
    public Vector3 vector;
    public float runSpeed;
    public float applyRunSpeed; //눌렸을 때만 적용.
    

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()//매 프레임 실행
    {

        if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") == 0) {
            vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z);


            if (Input.GetKey(KeyCode.LeftShift)) {
                applyRunSpeed = runSpeed;
            }
            else
            {
                applyRunSpeed = 0;
            }
        }
        
        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);
        }
    }
}

 

 

컴파일하면 코드가 정상 작동하는 것을 확인할 수 있다. 

 

이건 픽셀단위로 움직이는데, 파일 단위로 움직이도록 수정을 해준다. 

 

연산 과정에서 파일 단위로  너무 빨리 이동하기 때문에 wait 연산이 필요함.

코루틴 코드 추가

-> 대기 명령어를 가짐

 

 

 

using System.Collections;
using UnityEngine;

public class MovingBehavi : MonoBehaviour
{
    public float speed;
    public Vector3 vector;
    public float runSpeed;
    private float applyRunSpeed; //눌렸을 때만 적용.

    public int walkCount; //
    private int currentWalkCount;

    private bool canMove=true;
    //speed * walkCOunt  픽셀만큼 한번에 이동하겠다. 
    //while 안에서 walkcount 만큼 currentWalkCount변수를 통해 반복하고 이가 종료되면 한번에 움직인다. 


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    IEnumerator MoveCoroutine() {
        vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z);

        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);
            }
            currentWalkCount++;
        }
        currentWalkCount = 0;

        if (Input.GetKey(KeyCode.LeftShift))
        {
            applyRunSpeed = runSpeed;
        }
        else
        {
            applyRunSpeed = 0;
        }

    yield return new WaitForSeconds(1f);
        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());
            }
        }
    }
}

 

 

 

여기서  yield return new WaitForSeconds(1f); 문을 while  문 안으로 이동해서 넣어주면 더욱 자연스러운 움직임이 가능하다. 

 

shilf  키를 누르면 두칸씩 움직이게 되는데 이를 위해 코드를 더 수정해준다. 

 

using System.Collections;
using UnityEngine;

public class MovingBehavi : MonoBehaviour
{
    public float speed;
    public Vector3 vector;
    public float runSpeed;
    private float applyRunSpeed; //눌렸을 때만 적용.

    public int walkCount; //
    private int currentWalkCount;

    private bool canMove=true;

    private bool applyRunFlag=false;
    //speed * walkCOunt  픽셀만큼 한번에 이동하겠다. 
    //while 안에서 walkcount 만큼 currentWalkCount변수를 통해 반복하고 이가 종료되면 한번에 움직인다. 


    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    IEnumerator MoveCoroutine() {
        vector.Set(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), transform.position.z);
        
        if (Input.GetKey(KeyCode.LeftShift))
        {
            applyRunSpeed = runSpeed;
            applyRunFlag = true;
        }
        else
        {
            applyRunSpeed = 0;
            applyRunFlag = false;
        }

        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;

      

   
        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());
            }
        }
    }
}

 

'솔룩스 > 유니티스터디' 카테고리의 다른 글

유니티강좌-5  (0) 2025.04.06
유니티강좌-4  (0) 2025.04.06
유니티강좌-3  (0) 2025.04.06
유니티강좌-2  (0) 2025.04.06