728x90

목차.

  1. 개요
  2. 소스코드
  3. 코드분석
  4. 결과

 

개요

 

이번 글에서 유니티 3D에서 스페이스바를 이용해 점프 기능을 구현해 보겠습니다.

 

코드를 작성하기 전 점프를 할 오브젝트에게 RigidBody 컴포넌트를 추가해줘야 합니다.

점프 기능을 추가할 오브젝트를 Hierarchy 창에서 클릭-> Add Component -> Rigidbody 검색 후 추가

 

Rigidbody 컴포넌트를 추가해야 하는 이유는?

-AddForce를 이용하여 Rigidbody에 힘을 가함으로써 오브젝트가 점프하는 듯한 효과를 주기 위함입니다

 

소스코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    Rigidbody pRigidbody;
    float jumpForce = 5.0f;
    bool grounded = false;
  
    void Start()
    {
        pRigidbody = GetComponent<Rigidbody>();
    }
    public void Update()
    {
        Jump();
        CheckGround();
    }

    private void Jump()
    {
        if (Input.GetButtonDown("Jump") && grounded)
        {
            //Sqrt 는 빠른 속도로 점프 하고 천천히 낙하하는 부자연스러움을 줄여줌
            Vector3 jumpVelocity = Vector3.up * Mathf.Sqrt(jumpForce * -Physics.gravity.y);

            pRigidbody.AddForce(jumpVelocity, ForceMode.Impulse);
        }
    }
   
    //플레이어 바닥과 충돌 체크
    private void CheckGround()
    {
        RaycastHit hit;
        if (Physics.Raycast(pTransform.position, Vector3.down, out hit, 0.1f))
        {
            if (hit.transform.tag !=null)
            {
                grounded = true;
                return;
            }
        }
        grounded = false;
    }
  
}

 

코드분석

 

핵심 코드는 Jump 함수와 CheckGround 이렇게 두 개의 함수입니다.

 

Jump함수

 

AddForce의 형태는 다음과 같습니다.

-AddForce(Vector3 force, ForceMode mode =ForceMode.Force);

 

Vector3 : 힘을 가할 방향을 뜻합니다.

ForceMode : Acceleration , Force, Impulse, VelocityChange 가 있는데,

저는 순간 강력한 힘을 주는 Impulse를 사용하였습니다.

만약 VelocityChange를 이용하면 비슷한 속도로 점프를 하기 때문에 부자연스럽다는 문제점이 있었습니다.

 

Rigidbody.AddForce의 자세한 설명은 유니티 공식문서를 확인하면 됩니다.

 

Unity - Scripting API: Rigidbody.AddForce

Force is applied continuously along the direction of the force vector. Specifying the ForceMode mode allows the type of force to be changed to an Acceleration, Impulse or Velocity Change. The effects of the forces applied with this function are accumulated

docs.unity3d.com

CheckGround 함수

 

플레이어가 점프를 하는 조건에서 grounded가 있습니다.

grounded가 true일 때, 즉 바닥에 있을 때 점프를 하고

false일 때, 즉 공중에 있을 때는 점프를 하지 못하게 해야 합니다.

 

저는 이번에 Physics.Raycast를 사용했습니다.

- Physics.Raycast(Vector3 위치, Vector3 방향, out 결과물, float 길이);

 

 

플레이어 위치에서 밑으로 Ray를 발사했고 Ray가 충돌한 물체의 태그가 null이 아니라면 즉,

공중이 아니라면 grounded를 true로 만들어줬습니다.

 

반대로 null이라면 grounded가 false 되도록 했습니다.

 

Physics.Raycast는 정말 많은 사용 방법이 있고 유용한 기능입니다.

 

결과

 

이제 게임을 실행해서 스페이스바를 누르면 플레이어가 점프하는 것을 볼 수 있습니다.

이번 글에서 Rigidbody.AddForce를 사용해 오브젝트에 힘을 가하는 것과,

Physics.Raycast를 사용해 오브젝트의 정보를 받아오는 것을 해봤습니다.

728x90

+ Recent posts