본문 바로가기
Programming/Unity

[Unity] 플레이어 점프와 이동, 플레이어를 따라가는 카메라, 점프 중 이동 제어

by happy_jinsu 2021. 10. 14.

< 점프 & 이동 & 카메라 고정 구현>

 

1. 기능 구현에 필요한 플레이어, 방해물, 땅을 생성한다. (방해물에 기능은 나중에 추가)

플레이어, 땅, 방해물


2. 카메라가 플레이어에게 고정될 수 있도록 하기 위해 스크립트를 생성하여 카메라에 넣어준다. 카메라가 따라갈 대상을 꼭 Player에 Drag&Drop 해준다. 편의를 위해  FollowCam안의 인스턴스 변수의 이름도 Player로 설정했다.

 

카메라 위치 조정의 편이를 위해 public으로 스크립트 외부에서 조작 가능하도록 함.

 

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

public class FollowCam : MonoBehaviour
{
    public GameObject player;
    public float x, y, z;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.transform.position + new Vector3(x, y, z);
    }
}

3. 플레이어에게 중력을 걸어주기 위해 Add Component - Rigidbody 한다. 이때, 플레이어를 동그란 구로 설정했기 때문에 굴러가는 것을 방지하기 위해 Freeze Rotation X, Z 박스를 체크해준다. 그리고 플레이어가 점프 및 좌우 이동을 할 수 있도록 스크립트를 넣어준다.

리지드바디 추가, 스크립트 추가 한 모습

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

public class Player : MonoBehaviour
{
    public Rigidbody rigid;

    public int JumpPower;
    public bool IsJumping;

    // 처음 한번만 실행 되는 함수
    void Start()
    {
        rigid = GetComponent<Rigidbody>();
        IsJumping = false;
    }
    // 매 frame마다 실행 되는 함수
    void Update()
    {
        Jump();

        if (Input.GetKey(KeyCode.LeftArrow))  //왼쪽
        {
            if (IsJumping==false)       //점프 중에는 이동 불가
            {
                this.transform.Translate(-0.1f, 0.0f, 0.0f);
            }

            else
            {
                return;
            }
        }

        if (Input.GetKey(KeyCode.RightArrow))  //오른쪽
        {
            if (IsJumping == false)     //점프 중에는 이동 불가
            {
                this.transform.Translate(0.1f, 0.0f, 0.0f);
            }

            else
            {
                return;
            }
        }
    }

    void Jump()
    {
   
        if(Input.GetKeyDown(KeyCode.Space))
        {
            if(!IsJumping)     //땅에 닿았을 때만 다시 점프 가능
            {
                IsJumping = true;
                rigid.AddForce(Vector3.up * JumpPower, ForceMode.Impulse);
            }

            else
            {
                return;
            }
        }
    }

    private void OnCollisionEnter(Collision collision)       // 땅에 닿지 않으면 점프 불가
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            IsJumping = false;
        }
    }
}

4. 위의 Player 스크립트에서는 "Ground" 태그를 활용하기 때문에 태그도 생성해준다. 기존 태그에 없는 경우, Add Tag를 통해 추가하여 등록해준다.

태그 등록

 


▶ 여기까지 하면 플레이어가 이동 할 때마다 카메라가 플레이어를 따라가고, 플레이어는 점프를 하며 점프 중이지 않을 때는 좌우로 이동할 수 있다.