Unity/Theory

[Unity] (New) Input System - Jump

JEE_YA 2025. 3. 6. 21:01

 

Move를 진행하면서 생각보다 점프도 간단하겠지 싶었는데 아니었다, 그래서 정리해보았다.

Jump는 스페이스바로 지정해주었다.

public class PlayerController : MonoBehaviour
{
    [Header("Moverment")]
    public float jumpPower;
    // 플레이어를 레이어 마스크에서 빼주기 (플레이어까지 감지하지 않게)
    public LayerMask groundLayerMask;
   
    public void OnJump(InputAction.CallbackContext context)
    {
    	// 점프키가 처음 눌린 순간에만 실행되도록 함
        if(context.phase == InputActionPhase.Started && IsGrounded())
        {
        	// y축으로 힘을 추가해서 점프 구현
            _rigidbody.AddForce(Vector2.up * jumpPower, ForceMode.Impulse);
        }
    }
	
    // 바닥감지용. 플레이어가 바닥에 있는지 확인하는 함수, 공중에선 점프하지 못하게 막음
    bool IsGrounded()
    {
    	// 4개의 레이를 생성, transform.position 기준으로 상하좌우 네방향에서 아래쪽(Vector3.Down)으로 쏨
        Ray[] rays = new Ray[4]
        {
            new Ray(transform.position + (transform.forward * 0.2f) + (transform.up * 0.01f), Vector3.down),
            new Ray(transform.position + (-transform.forward * 0.2f) + (transform.up * 0.01f), Vector3.down),
            new Ray(transform.position + (transform.right * 0.2f) + (transform.up * 0.01f), Vector3.down),
            new Ray(transform.position + (-transform.right * 0.2f) + (transform.up * 0.01f), Vector3.down)
        };
        
        for(int i = 0; i < rays.Length; i++)
        {
            // 0.1정도 짧은 거리에 레이를 쏘는것, 시작해서 바닥을 감지
            // physics.Raycast()를 사용하여 레이어마스크와 충돌하는지 확인
            if (Physics.Raycast(rays[i], 0.1f, groundLayerMask))
            {	
            	// 바닥과 닿는 레이가 있으면 true를 반환
                return true;
            }
        }

		// 네개의 레이가 모두 공중이라면 공중에 떠있는 상태로 인식하여 false
        return false;
    }
}

 

  • ForceMode.Impulse : 즉시 강한 힘을 주는 모드

 

IsGrounded가 없이도 점프 로직은 잘 실행되나 공중에 있는 상태에서 스페이스바를 여러번 누르면 무한 점프가 된다.

점프를 한번만 하기위해 IsGrounded 함수를 만들어주었다