본문 바로가기
C#

[C#][Unity] 캐릭터 점프 기능 만들기

by teamnova 2021. 9. 14.

안녕하세요? 

저번 포스팅에 이어서 유닛에 점프 기능을 스틱코드를 이용해서 만들어보겠습니다.

 

실행 환경

개발 툴: Unity 2020.3.9f1

IDE : Rider


이전에 만들어 뒀던 프로젝트를 실행 후 MoveScript C# 파일을 클릭해서 실행해줍니다.


다음 예제에 사용할 코드를 작성해보겠습니다.

 

스틱 코드를 활용한다면, 클래스에서 'j' 까지만 작성했을 때 '유닛 점프 기능 생성' 이벤트가 나타납니다.

'유닛 점프 기능 생성' 이벤트를 누를 경우 코드가 자동으로 완성됩니다.

함수를 사용하기 위해 FixedUpdate() 함수 안에 아래 사진처럼 함수 이름을 추가해줍니다.

<최종 코드>

using UnityEngine;

public class MoveScript : MonoBehaviour
{
    bool isJump = false;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Move();
        Jump();
    }
    
    void Move() {
           float _speed = 10f;
    
           // Quaternion.LookRotation: 벡터 매개변수의 방향으로 쳐다보게끔 자신의 방향을 회전시켜주는 함수
           // Quaternion.Slerp: 좀 더 부드럽게 회전시켜주는 함수
           if (Input.GetKey(KeyCode.W)) {
               transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.back), 0.2f); 
               transform.position += Vector3.back * Time.deltaTime * _speed;
           }
           
           if (Input.GetKey(KeyCode.S)) {
               transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.forward), 0.2f); 
               transform.position += Vector3.forward * Time.deltaTime * _speed;
           }
           
           if (Input.GetKey(KeyCode.A)) {
               transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.right), 0.2f); 
               transform.position += Vector3.right * Time.deltaTime * _speed;
           }
           
           if (Input.GetKey(KeyCode.D)) {
               transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.left), 0.2f); 
               transform.position += Vector3.left * Time.deltaTime * _speed;
           }
       }
    
    void Jump () {
        if (Input.GetKeyDown(KeyCode.Space)) {
            
            //위쪽으로 힘을 준다.
            Rigidbody Rigidbody = transform.GetComponent<Rigidbody>();
            Rigidbody.AddForce(Vector3.up * 5, ForceMode.Impulse);
        }
    }
}

프로젝트를 실행하면 아래 사진같이 키보드 스페이스바를 입력하면 오브젝트가 점프하는 것을 확인할 수 있습니다.