ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 유니티 웅크리기 구현 - 플레이어 웅크리기
    Unity 2024. 2. 3. 21:37
    반응형

    안녕하세요

    오늘은 저번 시간에 진행한 플레이어 이동에 이어서 웅크리기를 구현했습니다.


    [인스펙터]

    • 설정된 값 입니다.
    • 함수를 작성하면서 값을 임의로 변경해 테스트 해보세요
    • 모든 함수는 PlayerMovement.cs에서 작성되었습니다.

    [변수]

    • 웅크리기 상태일때 속도
    • 웅크리기를 눌렀을 때 플레이어 크기
    • 웅크리기 시작 전 플레이어 크기

    [상태]

    • 각 움직임에 따른 상태를 만들어 줍니다.
    • FSM으로 구현해도 좋습니다.

    [초기화]

    /** 초기화 */
    private void Start()
    {
        rigid.freezeRotation = true;
    
        // 점프 초기화
        PlayerResetJump();
    
        crouchStartScaleY = this.transform.localScale.y;
    }
    • 웅크리기 시작전 Scale Y 값을 현재 플레이어 Scale Y 값으로 지정해 줍니다.

    [PlayerInput()]

    /** 입력처리 */
    private void PlayerInput()
    {
        // 움직임
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");
        
        // 점프
        if(Input.GetKey(jumpKey) && isJump && isGround)
        {
            isJump = false;
    
            // 점프
            PlayerJump();
    
            // 점프 쿨타임
            Invoke(nameof(PlayerResetJump), jumpCooldown);
        }
    
        // 웅크리기 시작
        if (Input.GetKeyDown(crouchKey))
        {
            this.transform.localScale = new Vector3(this.transform.localScale.x, crouchScaleY, this.transform.localScale.z);
            rigid.AddForce(Vector3.down * 5f, ForceMode.Impulse);
        }
    
        // 웅크리기 해제
        if (Input.GetKeyUp(crouchKey))
        {
            this.transform.localScale = new Vector3(this.transform.localScale.x, crouchStartScaleY, this.transform.localScale.z);
        }
    }
    • 플레이어 입력처리 함수에 웅크리기 시작, 해제를 구현했습니다.
    • 웅크리기 시작 부분에서, 크기를 축소하면 공중에 약간 떠 있기 때문에 AddForce를 이용해 바닥에 밀어넣습니다.

    [MovementStateHandler()]

    /** 이동 상태 제어 */
    private void MovementStateHandler()
    {
        // 웅크리기
        if (Input.GetKey(crouchKey))
        {
            movementState = MovementState.crouch;
            moveSpeed = crouchSpeed;
        }
    
        // 달리기
        if(isGround && Input.GetKey(sprintKey))
        {
    
            movementState = MovementState.sprint;
            moveSpeed = sprintSpeed;
        }
        // 걷기
        else if (isGround)
        {
            movementState = MovementState.walk;
            moveSpeed = walkSpeed;
        }
        // 공중
        else
        {
            movementState = MovementState.air;
    
        }
    }
    • 키 입력에 따라 상태를 정하고, 속도를 정합니다.
    • Update() 함순에서 호출해줍니다.

    [결과]

    반응형
Designed by Tistory.