솔룩스/유니티스터디

유니티강좌-3

조강학 2025. 4. 6. 04:49

이동불가 설정

 

캐릭터에 박스콜라이더를 추가한다. 

 

 

레이어 마스크 설정됨.

 

레이어를 추가해주고

해당 레이어를 인스펙터에서 레이어 마스크 값으로 사용한다 .

 

 

 

박스에 박스콜라이더 설정을 추가하고 여기 레이어를 nopassing으로 주면 더이상 통과할 수 없다

using System.Collections;
using UnityEngine;

public class MovingBehavi : MonoBehaviour
{
    private BoxCollider2D boxCollider;
    public LayerMask layerMask;//어떤 레이어랑 부딪힌건지

    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변수를 통해 반복하고 이가 종료되면 한번에 움직인다. 


    private Animator animator;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    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;
            }
            if (vector.y != 0)
            {
                vector.x = 0;
            }
            animator.SetFloat("DirX", vector.x);
            animator.SetFloat("DirY", vector.y);
            //이동 불가 설정
            RaycastHit2D hit;//중간에 뭐가 부딪히면 그거 return 

            Vector2 start=transform.position;//현재
            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());
            }
        }
    }
}

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

유니티강좌-6  (0) 2025.04.13
유니티강좌-5  (0) 2025.04.06
유니티강좌-4  (0) 2025.04.06
유니티강좌-2  (0) 2025.04.06
유니티강좌-1  (0) 2025.04.06